一、cpu使用率监测
1.首先需要给与app读取系统底层日志的权限
<uses-permission android:name="android.permission.READ_LOGS" />
2.通过读取系统日志计算出短时间内设备的cpu使用率(0~100):
/**
* 读取当前cpu使用率
*/
public int readUsage()
{
try
{
BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream( "/proc/stat" ) ), 1000 );
String load = reader.readLine();
reader.close();
String[] toks = load.split(" ");
long currTotal = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4]);
long currIdle = Long.parseLong(toks[5]);
long sum=(currTotal - total + currIdle - idle);
if (sum>0){
this.usage =(currTotal - total) * 100.0f /sum ;
}
this.total = currTotal;
this.idle = currIdle;
}
catch( IOException ex )
{
ex.printStackTrace();
}
return (int) this.usage;
}
二、内存使用监测—>当前app使用大小
public static int getMemPer(Context context){
if (context==null){
return 0;
}
ActivityManager activityManager= (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
int[] pids=new int[1];
pids[0]= Process.myPid();
Debug.MemoryInfo[] processMemoryInfo = activityManager.getProcessMemoryInfo(pids);
Debug.MemoryInfo memoryInfo = processMemoryInfo[0];
Debug.getMemoryInfo(memoryInfo);
int totalPss = memoryInfo.getTotalPss();
return totalPss;//单位kb
}