我正在使用此代码获取当前CPU温度:
也看到了it
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及以下(6,5,4)中的57.0
Android 7及更高版本(7,8,9)中的57000.0
我也尝试使用此代码:
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
txtCpuTemp.setText((cpu_temp / 1000) + " " + (char) 0x00B0 + "C");
}
但不起作用:(
如何在所有android版本中获得Temp ??
更新:
我更改类似的代码并在某些设备上工作 除了三星:
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");
}
答案 0 :(得分:2)
在较新的API上将值除以1000
:
float cpu_temp = getCurrentCPUTemperature();
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
cpu_temp = cpu_temp / 1000;
}
我只是想知道batteryTemp
的来源以及它与CPU
的关系。