Android获取实时cpu频率之Service于IntentService的

本文介绍了一种在Android设备上实时显示CPU内核频率的方法,通过对比普通Service和IntentService的使用,阐述了如何避免主线程阻塞,实现稳定的数据更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 解决了一个问题——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可以处理耗时任务。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值