我正在使用以下代码获取当前CPU温度:
并查看了此处
private float getCurrentCPUTemperature() {
String file = readFile("/sys/devices/virtual/thermal/thermal_zone0/temp", '\n');
if (file != null) {
return Long.parseLong(file);
} else {
return Long.parseLong(batteryTemp + " " + (char) 0x00B0 + "C");
}
}
private byte[] mBuffer = new byte[4096];
@SuppressLint("NewApi")
private String readFile(String file, char endChar) {
// Permit disk reads here, as /proc/meminfo isn't really "on
// disk" and should be fast. TODO: make BlockGuard ignore
// /proc/ and /sys/ files perhaps?
StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskReads();
FileInputStream is = null;
try {
is = new FileInputStream(file);
int len = is.read(mBuffer);
is.close();
if (len > 0) {
int i;
for (i = 0; i < len; i++) {
if (mBuffer[i] == endChar) {
break;
}
}
return new String(mBuffer, 0, i);
}
} catch (java.io.FileNotFoundException e) {
} catch (java.io.IOException e) {
} finally {
if (is != null) {
try {
is.close();
} catch (java.io.IOException e) {
}
}
StrictMode.setThreadPolicy(savedPolicy);
}
return null;
}
并像这样使用它:
float cpu_temp = getCurrentCPUTemperature();
txtCpuTemp.setText(cpu_temp + " " + (char) 0x00B0 + "C");
这段代码在 Android M 及以下版本运行良好,但在 Android N 及以上版本(7、8、9)无法正常工作,并以如下方式显示温度:
在 Android 6 及以下版本中显示为 57.0
在 Android 7 及以上版本中显示为 57000.0
我也尝试了以下代码:
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
txtCpuTemp.setText((cpu_temp / 1000) + " " + (char) 0x00B0 + "C");
}
但是不起作用 :(
我该如何在所有Android版本中获取温度?
更新:
我已经更改了代码,并且在某些设备上可以工作,但三星设备除外。
float cpu_temp = getCurrentCPUTemperature();
txtCpuTemp.setText(cpu_temp + " " + (char) 0x00B0 + "C");
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
txtCpuTemp.setText(cpu_temp / 1000 + " " + (char) 0x00B0 + "C");
}
txtCpuTemp.setText(cpu_temp / 1000 + " " + (char) 0x00B0 + "C"); }``` 我已经尝试过并且可以工作。但在Android 6下是否也能正常工作呢?
- Sana Ebadi@Override public void onReceive(Context context, Intent intent) { batteryTemp = (float) (intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0)) / 10; txtBatteryTemp.setText(batteryTemp + " " + (char) 0x00B0 + "C"); } };```
- Sana Ebadiif (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { txtCpuTemp.setText(cpu_temp / 1000 + " " + (char) 0x00B0 + "C"); }```
- Sana Ebadi