如何以编程方式获取android cpu温度

时间:2018-08-21 12:29:11

标签: android cpu temperature

对此进行了尝试,但得到了0.0,并且在物理设备上找不到任何内容。 在Android中获取CPU温度的任何方法

SensorManager mySensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    Sensor AmbientTemperatureSensor
            = mySensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
    if (AmbientTemperatureSensor != null) {
        mySensorManager.registerListener(
                AmbientTemperatureSensorListener,
                AmbientTemperatureSensor,
                SensorManager.SENSOR_DELAY_NORMAL);
    }

私有的最终SensorEventListener AmbientTemperatureSensorListener             = new SensorEventListener(){

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_AMBIENT_TEMPERATURE) {
            temperature = event.values[0];
            Messages.sendMessage(getApplicationContext(),Float.toString(temperature));
        }
    }

};

2 个答案:

答案 0 :(得分:1)

public static float cpuTemperature()
{
    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();
        if(line!=null) {
            float temp = Float.parseFloat(line);
            return temp / 1000.0f;
        }else{
            return 51.0f;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return 0.0f;
    }
}

答案 1 :(得分:0)

有针对此类内容的系统服务 HardwarePropertiesManager ,其中包含方法getDeviceTemperatures(int type, int source),可从Nougat

获得
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    HardwarePropertiesManager hardwarePropertiesManager= (HardwarePropertiesManager) getSystemService(Context.HARDWARE_PROPERTIES_SERVICE);
     float[] temp = hardwarePropertiesManager.getDeviceTemperatures(HardwarePropertiesManager.DEVICE_TEMPERATURE_CPU, HardwarePropertiesManager.TEMPERATURE_CURRENT);
}

看看这个: https://developer.android.com/reference/android/os/HardwarePropertiesManager