Android 获取手机 cpu 温度,你还不知道的超级方案

1. 前言

记得刚来公司 4 个多月的时候,公司的一个产品问我:可以获取 Android cpu 的温度吗?我答道:如果别人可以,我们也可以获取到。其实,我那时确实不知道怎么获取,也没具体去看这个问题。等到最近确实需要这个功能时,实在是找了好多资料,才找到了方案。现在想想,那时回答的实在是很轻率啊。

2. 正文

2.1 两种可选方案

查询网上的文章,有两种方案:
1,通过读取温度传感器的值近似作为 cpu 的温度:这个方案在没有温度传感器的手机上行不通;再者,这也是近似的温度,并不是 cpu 真正的温度;
2,通过读取 cpu 内核信息获取温度:这个方法直接也准确,但是到底读取哪些信息呢?资料并不充分。

2.2 采取的方案

本文采取的是第二种方案。
经过查询资料,有更多的备选可以读取。可以查看下面的类:

public class CpuUtils {
    private CpuUtils() {
        //no instance
    }
    private static final List<String> CPU_TEMP_FILE_PATHS = Arrays.asList(
            "/sys/devices/system/cpu/cpu0/cpufreq/cpu_temp",
            "/sys/devices/system/cpu/cpu0/cpufreq/FakeShmoo_cpu_temp",
            "/sys/class/thermal/thermal_zone0/temp",
            "/sys/class/i2c-adapter/i2c-4/4-004c/temperature",
            "/sys/devices/platform/tegra-i2c.3/i2c-4/4-004c/temperature",
            "/sys/devices/platform/omap/omap_temp_sensor.0/temperature",
            "/sys/devices/platform/tegra_tmon/temp1_input",
            "/sys/kernel/debug/tegra_thermal/temp_tj",
            "/sys/devices/platform/s5p-tmu/temperature",
            "/sys/class/thermal/thermal_zone1/temp",
            "/sys/class/hwmon/hwmon0/device/temp1_input",
            "/sys/devices/virtual/thermal/thermal_zone1/temp",
            "/sys/devices/virtual/thermal/thermal_zone0/temp",
            "/sys/class/thermal/thermal_zone3/temp",
            "/sys/class/thermal/thermal_zone4/temp",
            "/sys/class/hwmon/hwmonX/temp1_input",
            "/sys/devices/platform/s5p-tmu/curr_temp");

    public static final Maybe<CpuTemperatureResult> getCpuTemperatureFinder() {
        return Observable
                .fromIterable(CPU_TEMP_FILE_PATHS)
                .map(new Function<String, CpuTemperatureResult>() {
                    @Override
                    public CpuTemperatureResult apply(String path) {
                        Double temp = readOneLine(new File(path));
                        String validPath = "";
                        double currentTemp = 0.0D;
                        if (isTemperatureValid(temp)) {
                            validPath = path;
                            currentTemp = temp;
                        } else if (isTemperatureValid(temp / (double) 1000)) {
                            validPath = path;
                            currentTemp = temp / (double) 1000;
                        }

                        return new CpuTemperatureResult(validPath, (int) currentTemp);
                    }
                }).filter(new Predicate<CpuTemperatureResult>() {
                    @Override
                    public boolean test(CpuTemperatureResult cpuTemperatureResult) throws Exception {
                        return !TextUtils.isEmpty(cpuTemperatureResult.getFilePath())
                                && (cpuTemperatureResult.getTemp() != 0);
                    }
                }).firstElement();
    }

    private static double readOneLine(File file) {
        FileInputStream fileInputStream = null;
        String s = "";
        try {
            fileInputStream = new FileInputStream(file);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            s = bufferedReader.readLine();
            fileInputStream.close();
            inputStreamReader.close();
            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        double result = 0;
        try {
            result = Double.parseDouble(s);
        } catch (NumberFormatException ignored) {
        }
        return result;
    }

    private static boolean isTemperatureValid(double temp) {
        return temp >= -30.0D && temp <= 250.0D;
    }


}

上面的代码用到了 RxJava 的操作符来处理集合的遍历。思路就是遍历读取集合中的文件,获取到信息;判断符合条件,就作为 cpu 的温度;如果都不符合,那么就读取不到 cpu 的温度。
这个方案也不是兼容所有的手机的,但是确实兼容性比较高。

3. 最后

感谢这个开源项目:https://github.com/kamgurgul/cpu-info,提供了较为完备的解决方案。

参考

1,Android获取手机Cpu温度
2,https://github.com/kamgurgul/cpu-info

Android 中,获取 CPU 和 GPU 各核的温度可以使用系统提供的接口和传感器来实现。以下是一个示例代码,演示如何获取 CPU 和 GPU 的温度: ```java import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.view.View; import android.widget.Button; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; public class TemperatureActivity extends AppCompatActivity { private TextView cpuTempTextView, gpuTempTextView; private Button startButton, stopButton; private Handler mHandler; private Runnable mRunnable; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_temperature); cpuTempTextView = findViewById(R.id.cpu_temp_text_view); gpuTempTextView = findViewById(R.id.gpu_temp_text_view); startButton = findViewById(R.id.start_button); stopButton = findViewById(R.id.stop_button); mHandler = new Handler(Looper.getMainLooper()); startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startMonitoring(); } }); stopButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { stopMonitoring(); } }); } private void startMonitoring() { mRunnable = new Runnable() { @Override public void run() { float cpuTemp = getCPUTemperature(); float gpuTemp = getGPUTemperature(); cpuTempTextView.setText("CPU Temperature: " + cpuTemp + "°C"); gpuTempTextView.setText("GPU Temperature: " + gpuTemp + "°C"); mHandler.postDelayed(this, 1000); // 每隔1秒更新一次温度 } }; mHandler.post(mRunnable); } private void stopMonitoring() { mHandler.removeCallbacks(mRunnable); } private float getCPUTemperature() { try { File file = new File("/sys/class/thermal/thermal_zone0/temp"); FileInputStream fis = new FileInputStream(file); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String temp = br.readLine(); br.close(); fis.close(); int cpuTemp = Integer.parseInt(temp); return cpuTemp / 1000.0f; // 将温度转换为摄氏度并返回 } catch (IOException e) { e.printStackTrace(); } return 0.0f; } private float getGPUTemperature() { // 获取 GPU 温度的方法因设备而异,请根据实际情况自行查阅文档或资料 // 并在此处实现获取 GPU 温度的逻辑 // 这里只是一个示例,返回一个固定值 45.5°C return 45.5f; } } ``` 以上示例代码中,通过读取 `/sys/class/thermal/thermal_zone0/temp` 文件来获取 CPU 温度。请注意,不同设备的温度文件路径可能会有所不同,你需要根据实际情况进行调整。对于 GPU 温度获取,因为各个设备的实现方式不同,所以需要根据具体的设备和芯片厂商的文档或资料来查找对应的方法。 在示例中,点击 "Start" 按钮将开始监测 CPU 和 GPU 温度,每秒更新一次,点击 "Stop" 按钮将停止监测。温度数据会显示在对应的 TextView 上。 请注意,在实际应用中,为了确保代码的正常运行和适配不同的设备,你需要添加相应的权限和适配处理。同时,由于涉及到系统底层的温度读取,部分设备可能无法获取到正确的温度值。因此,在实际使用时需要注意测试和适配。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

willwaywang6

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值