- 解决了一个问题——Android内核cpu频率的实时显示;
起初思路是这样:启动一个服务,在服务中去检测cpu内核的实时频率,以1秒为间隔,然后得到数据进行广播,在主活动中获取cpu频率进行显示,OK开搞。
获取cpu内核数量的函数:
public static int getCpuNum() {
return Runtime.getRuntime().availableProcessors();
}
获取cpu内核频率函数:
public static String getCurCpuFreq(String cpuNum) {
String frequence = "N/A";
try {
FileReader fileReader = new FileReader("/sys/devices/system/cpu/" +
cpuNum + "/cpufreq/scaling_cur_freq");
BufferedReader bf = new BufferedReader(fileReader);
try {
String text = bf.readLine();
frequence = text.trim();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return frequence;
}
普通服务,service来实现:
@Override
public void onCreate() {
super.onCreate();
Frequency = new String[cores]; //记录内核频率的字符串;cores就是得到的内核数量,初始化时完成赋值;
/*
* 检测内核频率;
* 每1秒检测一次
* */
while (true) {
int index = 0;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
while (index < cores) {
Frequency[index] = getCurCpuFreq(kernel[index]);
// kernel[]数组记录的时cpu0-----cpu9共10个内核;
index++;
}
/*
* 发送广播,传递内核频率信息
* 在其它activity中定义广播接收器 接收此消息;
* */
Intent intent = new Intent();
intent.setAction(SIGNAL);
intent.putExtra("cpu_frequency", Frequency); //传递该内核频率数组;
intent.putExtra("Name", "Wechel");
sendBroadcast(intent);
}
结果。。。程序猝。。。
究其原因,发现,因为在该服务中要实现的是一个一直检测cpu内核频率的任务,非常耗时,一旦采用普通service来做的话,会阻塞主线程,而导致程序崩掉或者无返回结果。因此,正确的做法是采用IntentService来实现该功能。
IntentService来实现:
@Override
protected void onHandleIntent(Intent intent) {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
int index = 0;
while (index < cores) {
Frequency[index] = getCurCpuFreq(kernel[index]);
index++;
}
Intent intent1 = new Intent();
intent1.setAction(SIGNAL);
intent1.putExtra("CPU_FREQUENCY", Frequency);
sendBroadcast(intent1);
}
}
结果,perfect。。。
分析一波:
IntentService会使用队列来管理请求的Intent,每当客户端通过Intent请求启动IntentService时,IntentService会将该Intent加入到队列中,然后开启一个新的work线程来处理该Intent,因此,IntentService不会阻塞主线程,所以嘛。。。IntentService可以处理耗时任务。