san*_*adi 8 java cpu android temp
我正在使用此代码获取当前的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;
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
float cpu_temp = getCurrentCPUTemperature();
txtCpuTemp.setText(cpu_temp + " " + (char) 0x00B0 + "C");
Run Code Online (Sandbox Code Playgroud)
它的工作原理很吸引人,但适用于android M及以下版本。对于Android N及更高版本(7,8,9),请勿运行并显示以下温度:
Android 6及以下(6,5,4)中的57.0
Android 7及更高版本中的57000.0(7,8,9)
我也尝试以下代码:
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
txtCpuTemp.setText((cpu_temp / 1000) + " " + (char) 0x00B0 + "C");
}
Run Code Online (Sandbox Code Playgroud)
但不起作用:(
如何获得所有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");
}
Run Code Online (Sandbox Code Playgroud)
将值除以1000较新的 API:
float cpu_temp = getCurrentCPUTemperature();
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
cpu_temp = cpu_temp / 1000;
}
Run Code Online (Sandbox Code Playgroud)
我只是想知道batteryTemp它来自哪里以及它与CPU.
| 归档时间: |
|
| 查看次数: |
595 次 |
| 最近记录: |