DEV Community

Dhruv Joshi
Dhruv Joshi

Posted on • Updated on

How to code an Android app that shows CPU and battery temperatures?

To create an Android app that displays the CPU and battery temperatures, you can use the Android Debug Bridge (ADB) and the "cat" command to read the temperature values from the system files.

Here is some sample code that demonstrates how to use the ADB and "cat" command to display the CPU temperature in an Android app:

TextView tv = (TextView) findViewById(R.id.textview);

try {
    Process process = Runtime.getRuntime().exec("adb shell cat /sys/class/thermal/thermal_zone0/temp");
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line = reader.readLine();
    tv.setText(line + "°C");
} catch (IOException e) {
    e.printStackTrace();
}

Enter fullscreen mode Exit fullscreen mode

This code reads the temperature value from the "/sys/class/thermal/thermal_zone0/temp" file and displays it in a TextView with the unit "°C" (degrees Celsius). Note that you will need to have the ADB tool installed and configured on your computer, and the device must be connected to the computer via USB in order for the command to work.

To display the battery temperature, you can use the following code:

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = getApplicationContext().registerReceiver(null, ifilter);

int temperature = batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
tv.setText(temperature / 10.0 + "°C");

Enter fullscreen mode Exit fullscreen mode

This code uses the Intent.ACTION_BATTERY_CHANGED intent to get the battery temperature value, which is then divided by 10.0 and displayed in the TextView with the unit "°C".

I hope this helps! Let me know if you have any questions, you can reach me here.

Oldest comments (0)