繁体   English   中英

如何使用 java 获取 android 中的 CPU 温度?

[英]How to get the CPU Temperature in android using java?

'''

    Process process;
    try {
        process = Runtime.getRuntime().exec("cat sys/class/thermal/thermal_zone0/temp");
          
        process.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = reader.readLine();
        System.out.println("Multan "+ line);
        if(line!=null) {
            float temp = Float.parseFloat(line);
            return temp / 1000.0f;
        }else{
            return 51.0f;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return 0.0f;
    }

'''

我找到了这个解决方案,但它总是返回 51.0,因为行总是 null。 有人请帮忙。 提前致谢。

首先,像这样读取文件是错误的,您不需要每次想要获取温度时都创建一个新进程。

其次,您可能没有您要查找的文件。 这是因为 /sys/* 是系统创建的伪文件系统( sysfs ),它是不同的驱动程序。 它可能从一部手机到另一部非常不同。

我找到了一份非详尽的 cpu 温度文件列表。

String[] sensorFiles = new String[] {
    "/sys/devices/system/cpu/cpu0/cpufreq/cpu_temp",             
    "/sys/devices/system/cpu/cpu0/cpufreq/FakeShmoo_cpu_temp",    
    "/sys/class/thermal/thermal_zone1/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_zone0/temp",                      
    "/sys/devices/virtual/thermal/thermal_zone0/temp",            
    "/sys/class/hwmon/hwmon0/device/temp1_input",                 
    "/sys/devices/virtual/thermal/thermal_zone1/temp",           
    "/sys/devices/platform/s5p-tmu/curr_temp"
}

你必须尝试每一个,直到你得到一个肯定的答案。

File correctSensorFile = null;
for (String file : sensorFiles) {
    File f = new File(file);
    if (f.exists()) {
        correctSensorFile = f;
        break;
    }
}

if (correctSensorFile == null)
    throw new RuntimeException("Did not find sensor file to read");

RandomAccessFile reader = new RandomAccessFile(correctSensorFile , "r");
String value = reader.readLine();
reader.close();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM