如何在所有Android版本中以编程方式获取当前CPU温度



我正在使用此代码获取当前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");

它的工作就像一个魅力,但对于安卓 M 及以下。对于Android N及以上(7,8,9(不要工作并像这样显示温度:

安卓 6 及以下为 57.0 (6,5,4(

57000.0 在安卓 7 及更高版本中 (7,8,9(

我也尝试了这段代码:

 if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
      txtCpuTemp.setText((cpu_temp / 1000) + " " + (char) 0x00B0 + "C");
    }

但不能:(

工作

如何在所有安卓版本中获取 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");
    }

在较新的 API 上将值除以1000

float cpu_temp = getCurrentCPUTemperature();
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
    cpu_temp = cpu_temp / 1000;
}

我只是想知道batteryTemp来自哪里以及它应该如何与CPU相关.

最新更新