如何以编程方式在所有Android版本中获取当前的CPU温度? [英] how get current CPU temperature programmatically in all Android Versions?

查看:147
本文介绍了如何以编程方式在所有Android版本中获取当前的CPU温度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码获取当前的CPU温度:

I am using this code for get current CPU Temperature :

并看到了

and saw it too

 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),请勿运行并显示以下温度:

it is work like a charm but for android M and under. For Android N and above (7,8,9) Do not Work and Show The Temp like this :

在Android 6及以下版本中为57.0(6,5 ,4)

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 ??

How can I get the Temp in all android versions??

更新:

我更改类似的代码并在某些设备上工作
三星除外:

I change The code like it and work on some devices Except Samsung:

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

Divide the value by 1000 on newer API:

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

我只是想知道在哪里batteryTemp 的来源以及与 CPU 的关系。

I'd just wonder where batteryTemp comes from and how it should be related to the CPU.

这篇关于如何以编程方式在所有Android版本中获取当前的CPU温度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆