使用ViewServer让Android真机可用HierarchyView视图检测工具

使用ViewServer让Android真机可用HierarchyView视图检测工具

HierarchyViewer是Android SDK自带的用于布局检测的工具,其位置在\Android SDK目录\tools目录下,关于使用HierarchyView优化Android布局的方法,可以参考官方的这篇文章:http://developer.android.com/training/improving-layouts/optimizing-layout.html

但是该工具并不支持直接连接真机进行检测,连接真机时会报如下错误:


01:47:20 E/hierarchyviewer: Unable to get view server version from device e8ef8e7e
01:47:20 E/hierarchyviewer: Unable to get view server protocol version from device e8ef8e7e
01:47:20 E/ViewServerDevice: Unable to debug device: xiaomi-hm_note_1lte-e8ef8e7e
01:47:20 E/hierarchyviewer: Missing forwarded port for e8ef8e7e

01:47:20 E/hierarchyviewer: Unable to get the focused window from device e8ef8e7e


为了能够让该工具能够对真机使用,Android SDK开发团队提供了VIewServer开源库,项目地址https://github.com/romainguy/ViewServer

将该库引入项目,同时参考其中的ViewServerActivity即可,主要代码如下:

package com.android.debug.hv.sample;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.android.debug.hv.ViewServer;

public class ViewServerActivity extends Activity {
	private int mCounter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        if (getIntent().getExtras() != null) mCounter = getIntent().getExtras().getInt("counter");
        ((TextView) findViewById(R.id.label)).setText("Activity #" + (mCounter + 1));

        ViewServer.get(this).addWindow(this);
    }

    public void nextActivity(View v) {
    	Intent intent = new Intent(this, getClass());
    	intent.putExtra("counter", mCounter + 1);
		startActivity(intent);
    }

    @Override
    public void onDestroy() {
    	super.onDestroy();
    	ViewServer.get(this).removeWindow(this);
    }

    @Override
    public void onResume() {
    	super.onResume();
    	ViewServer.get(this).setFocusedWindow(this);
    }
}

只要在Activity的onCreate、onDestroy、onResume三个生命周期方法中调用ViewServer的对应方法即可在真机环境下使用HierarchyView工具

你可能感兴趣的:(个人总结)