手机开发者选项里面如何获取CPU运行信息的
做为Android开发者来说,应该对开发者选项是特别熟悉的。
通过【设置】->【开发者选项】->【显示cpu使用情况】这些步骤,可以看到CPU当前的情况。
这个功能的实现在系统的源码LoadAverageService类里实现的:com.android.systemui.LoadAverageService。
LoadAverageService是一个Service。
以5.1.1_r1为例,我们看到的CPU的实时的情况是在com.android.systemui.LoadAverageService里实现的:
LoadAverageService
有一个内部类LoadView
,用于展示CUP的实时情况,
数据从内部类CpuTracker
获取,这类继承自ProcessCpuTracker。所以我们的重点是看看ProcessCpuTracker
是如何获取CPU数据的。
LoadAverageService的代码只保留了主要结构和核心的代码:
package com.android.systemui;
import com.android.internal.os.ProcessCpuTracker;
public class LoadAverageService extends Service {
private View mView;
private static final class CpuTracker extends ProcessCpuTracker {
String mLoadText;
int mLoadWidth;
private final Paint mPaint;
CpuTracker(Paint paint) {
super(false);
mPaint = paint;
}
// 省略
}
private class LoadView extends View {
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 1) {
//重新获取一次数据
mStats.update();
updateDisplay();
Message m = obtainMessage(1);
//每两秒钟更新一次数据
sendMessageDelayed(m, 2000);
}
}
};
LoadView(Context c) {
super(c);
//省略了初始化绘制时需要的工具
//这里创建了CpuTracker对象,并进行了初始化
mStats = new CpuTracker(mLoadPaint);
mStats.init();
//更新展示,让CPU的情况绘制到屏幕上
updateDisplay();
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
//当View和Window关联后,第一次发送绘制的异步消息
mHandler.sendEmptyMessage(1);
}
//省略...
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
//省略
//获取CPU的相关信息,并做一定的运算
final CpuTracker stats = mStats;
final int userTime = stats.getLastUserTime();
final int systemTime = stats.getLastSystemTime();
final int iowaitTime = stats.getLastIoWaitTime();
final int irqTime = stats.getLastIrqTime();
final int softIrqTime = stats.getLastSoftIrqTime();
final int idleTime = stats.getLastIdleTime();
final int totalTime = userTime+systemTime+iowaitTime+irqTime+softIrqTime+idleTime;
if (totalTime == 0) {
return;
}
int userW = (userTime*W)/totalTime;
int systemW = (systemTime*W)/totalTime;
int irqW = ((iowaitTime+irqTime+softIrqTime)*W)/totalTime;
//绘制工作省略...
}
void updateDisplay() {
//View的高度宽度重新计算,主要用于判断是否重新绘制View还是重新进行测量。
if (neededWidth != mNeededWidth || neededHeight != mNeededHeight) {
mNeededWidth = neededWidth;
mNeededHeight = neededHeight;
requestLayout();
} else {
invalidate();
}
}
}
@Override
public void onCreate() {
super.onCreate();
//省略:把View add到屏幕上
WindowManager wm = (WindowManager)getSystemService(WINDOW_SERVICE);
wm.addView(mView, params);
}
//省略
}