how to get android cpu temperature programmatically
Asked Answered
C

3

6

Tried this but got 0.0 and on physical device nothing found.. Any way to get cpu temperature in android

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);
    }

private final 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));
        }
    }

};
Capo answered 21/8, 2018 at 12:29 Comment(1)
#65643538 this is exactly the answer of this question thanksGaribold
C
9
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;
    }
}
Capo answered 27/11, 2018 at 16:58 Comment(6)
SELinux problem. Permission denied.Seraphic
is this value degree celcius or farhenheit?Dhar
i don't exactly remember, it's been some time but i think it was farhenheit.Capo
From adb shell i getting correct value of temp. but using Runtime.getRuntime().exec("cat sys/class/thermal/thermal_zone0/temp"); I am getting null.Enplane
I get Permission Denied when trying to access sys files. Any workaround in this?Erfert
Does this works only on rooted devices?Pupil
T
6

You can find all the thermal values(temp and type) from this code (not only CPU temperature). And also remember that sys/class/thermal/thermal_zone0/temp not always point towards CPU temperature (in my case it was pointing towards battery temperature). Always use this code in background thread. I have tested it on real device as well as emulator and it was working fine.

public void thermal() {
        String temp, type;
        for (int i = 0; i < 29; i++) {
            temp = thermalTemp(i);
            if (!temp.contains("0.0")) {
                type = thermalType(i);
                if (type != null) {
                   System.out.println("ThermalValues "+type+" : "+temp+"\n"); 
                }
            }
        }
    }

    public String thermalTemp(int i) {
        Process process;
        BufferedReader reader;
        String line;
        String t = null;
        float temp = 0;
        try {
            process = Runtime.getRuntime().exec("cat sys/class/thermal/thermal_zone" + i + "/temp");
            process.waitFor();
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            line = reader.readLine();
            if (line != null) {
                temp = Float.parseFloat(line);
            }
            reader.close();
            process.destroy();
            if (!((int) temp == 0)) {
                if ((int) temp > 10000) {
                    temp = temp / 1000;
                } else if ((int) temp > 1000) {
                    temp = temp / 100;
                } else if ((int) temp > 100) {
                    temp = temp / 10;
                }
            } else
                t = "0.0";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }

    public String thermalType(int i) {
        Process process;
        BufferedReader reader;
        String line, type = null;
        try {
            process = Runtime.getRuntime().exec("cat sys/class/thermal/thermal_zone" + i + "/type");
            process.waitFor();
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            line = reader.readLine();
            if (line != null) {
                type = line;
            }
            reader.close();
            process.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return type;
    }

Sample Output in Logcat (Image below is Real device output... On emulator it only showed the type battery and its temperature.) :

Thermal Values

Thyrse answered 29/10, 2020 at 23:3 Comment(4)
Will this list contains Shutdown Temperature ?Uncial
It may vary from device to device. I am not pretty sure about Shutdown Temperature. But this is the only possible way to get the temperatures.Thyrse
You forgot t=Integer.toString((int)temp); At the end of the divide by conversionsCrabwise
how the ... your code work?Presidentelect
G
0

There is a system service for this kind of stuff HardwarePropertiesManager that contain a method getDeviceTemperatures(int type, int source) which is available from 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);
}

Take a look to this : https://developer.android.com/reference/android/os/HardwarePropertiesManager

Gustafsson answered 21/8, 2018 at 12:42 Comment(5)
Throws this exceptionCapo
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.faircode.netguard, PID: 17503 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.faircode.netguard/net.alimasood.cleanmaster.CpuCoolerActivity}: java.lang.SecurityException: The caller is not a device or profile owner r bound VrListenerService. at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)Capo
Sorry, but I just read that HardwarePropertiesManager API is only allowed in Enterprise configured Android devices :(Gustafsson
java.lang.SecurityException: The caller is not a device owner.Seraphic
"java.lang.SecurityException: The caller is neither a device owner, nor holding the DEVICE_POWER permission, nor the current VrListener." <uses-permission android:name="android.permission.DEVICE_POWER" />: "Permission is only granted to system apps"Amaty

© 2022 - 2024 — McMap. All rights reserved.