使用ddmlib实现android 性能监控
原理:
cpu
adb shell dumpsys cpuinfo packageName
memory
adb shell dumpsys meminfo packageName
流量
cat /proc/uid_stat/uidxxx/tcp_rcv
cat /proc/uid_stat/uidxxx/tcp_snd
其中 uid的获得通过
adb shell dumpsys package packageName
取得 userId=(\d+)\s
FPS刷新频率
这个计算稍微复杂,请参见源码:
sdk/sources/android-18/com/android/uiautomator/platform/SurfaceFlingerHelper.java(以android-18中的路径为例,其他版本中也有该文件,可能路径不同)
我写了个GUI
请联系 lizejun_qd@126.com,试用~
核心代码实现
控制器
public class AdbController {
protected static Logger logger = LoggerFactory.getLogger(AdbController.class);
protected static AndroidDebugBridge adb = null;
private static boolean isInit = false;
public AdbController() {
init();
}
public void init()
{
if(!isInit) {
AndroidDebugBridge.init(true);
DdmPreferences.setTimeOut(20000);
// adb = AndroidDebugBridge.createBridge(); //使用该方式,在没有启动adb时,会提示找不到
adb = AndroidDebugBridge.createBridge(ConfigurationSettings.ADB_PATH, false);
isInit = true;
}
waitDeviceList(adb);
}
private void waitDeviceList(AndroidDebugBridge bridge) {
int count = 0;
while (bridge.hasInitialDeviceList() == false) {
try {
Thread.sleep(100);
count++;
} catch (InterruptedException e) {
}
if (count > 100) {
System.out.println("Fail to Init Device list");
break;
}
}
}
public void terminate() {
if(deviceTimer!= null){
deviceTimer.clearService();
}
if(deviceListener!=null)
AndroidDebugBridge.removeDeviceChangeListener(deviceListener);
AndroidDebugBridge.terminate();
}
public IDevice[] getDevices() {
return adb.getDevices();
}
public IDevice getCurrentDevice() {
return deviceListener.mCurrentDevice;
}
public IDevice getDevice(String serialNum) {
IDevice[] devices = adb.getDevices();
int nums = devices.length;
for (int i = 0; i < nums; i++) {
String curSerialNum = devices[i].getSerialNumber();
if (serialNum.equals(curSerialNum))
return devices[i];
}
return null;
}
public String getCurrentActivity(String monitorPackage){
SFActivityService sf = new SFActivityService(getCurrentDevice(), monitorPackage);
sf.executeCmd();
return sf.getCurActivity();
}
}
CPU
/**
* 使用 dumpsys cpuinfo xxx.package.name 获取Cpu的性能指标
* @author zejun.lzj
*
*/
public class CpuInfoService extends Observable implements AdbShellService {
protected IDevice device;
private CpuInfoReceiver receiver = null;
protected String monitorPackage;
public CpuInfoService(IDevice device,String monitorPackage) {
this.device = device;
this.monitorPackage = monitorPackage;
receiver = new CpuInfoReceiver(); }
public Float getCpuRatio(){
Float cpuRatio = receiver.getCpuRatio();
if(cpuRatio == null || cpuRatio <0 )
cpuRatio = -1f;
return cpuRatio;
}
public void executeCmd() {
if(StringUtils.isEmpty(monitorPackage))
return;
String cmd = "dumpsys cpuinfo " + monitorPackage;
try {
device.executeShellCommand(cmd, receiver);
} catch (TimeoutException e) {
logger.error(LOG_TAG,"TimeoutException");
e.printStackTrace();
} catch (AdbCommand