簡體   English   中英

如何在所有Android版本中以編程方式獲取當前CPU溫度?

[英]how get Current CPU Temperature programmatically in all Android Versions?

我正在使用此代碼獲取當前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,5)中的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");
    }

但不工作:(

我怎樣才能在所有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");
    }

在較新的API上將值除以1000

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

我只是想知道batteryTemp來自哪里以及它應該如何與CPU相關。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM