How to code an Android app that shows CPU and battery temperatures?
Dhruv Joshi
Posted on December 30, 2022
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();
}
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");
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.
Posted on December 30, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
December 31, 2022