使用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 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工具