Enabling HierarchyViewer on any retail phone

Sunday, January 27, 2013

The HierarchyViewer is an Android SDK tool that gives developers the ability to introspect on all aspects of an application's layout at runtime. The tool can be extremely useful for developers when debugging the view state of an application across a realm of devices.

So how does it actually work? The HierarchyViewer utilizes a service running on the device called ViewServer. When launched, ViewServer opens up a socket on local port 4939 and receives commands from a client (usually HierarchyViewer) to dump the current view state of the device. The ViewServer dispatches these calls via binder to the ViewRoot class, which serializes the view state and transmits it to the client over the socket. The WindowManagerService manages the ViewServer and provides a hook (via binder service call) to spawn the service.

Unfortunately, due to security reasons HierarchyViewer does not work on retail phones. However, it is possible to overcome this restriction by using Romain Guy's ViewServer inside your application.

The recommended way to use this API is to register activities when they are created, and to unregister them when they get destroyed:
public class MyActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
     public void onDestroy() {
     public void onResume() {
Don't forget to modify AndroidManifest.xml file to request INTERNET permission, otherwise you will get nasty exceptions:

As a result you will be able to use HierarchyViewer with any device:

Final remarks: Sometimes it's useful to build ViewServer as an Android library project so it can is used by several Android projects.


[1] Using Hierarchy Viewer.

[2] Enabling HierarchyViewer on Rooted Android Devices. 2012.

[3] Android Tools: Using the Hierarchy Viewer.