rss

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) {
         super.onCreate(savedInstanceState);
         ViewServer.get(this).addWindow(this);
     }
 
     public void onDestroy() {
         super.onDestroy();
         ViewServer.get(this).removeWindow(this);
    }
 
     public void onResume() {
         super.onResume();
         ViewServer.get(this).setFocusedWindow(this);
    }
}
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.


References

[1] Using Hierarchy Viewer. http://developer.android.com/tools/debugging/debugging-ui.html

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

[3] Android Tools: Using the Hierarchy Viewer. http://mobile.tutsplus.com


0 comments: