在Android Studio的开发过程中,打开HierarchyView,连接真机会出现Unable to get view server version from device ...的报错。
出现该问题的原因是:
To preserve security, Hierarchy Viewer can only connect to devices running a developer version of the Android system
即:出于安全考虑,Hierarchy Viewer只能连接Android开发版手机或是模拟器。市面上的手机一般都不满足该条件(ro.debuggable = 1)
参考 http://www.cnblogs.com/coding-way/p/4294225.html ,可知Hierarchy View的原理是通过创建ServerSocket,监听4939端口,ViewServer处理响应命令。github上有一开源库可供参考。
ViewServer
github地址:https://github.com/romainguy/ViewServer
使用方法:

image.png
但是实际测试时,gradle sync失败,无法获取ViewServer:-SNAPSHOT。最终我将下载的github源码编译为aar文件导入解决工程问题。
注意:app必须申请Internet权限
使用示例
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set content view, etc.
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);
}
}
重新运行app后,打开Hierarchy View即可。效果如下图:

image.png