Android如何實現獲取手機CPU的溫度?
在做專案過程中,有時需要獲取手機CPU的溫度。
目前市面上常見的CPU主要有兩種:MTK(聯發科)、Qualcomm(高通)。當然還有我們華為的海思麒麟CPU,以及三星的CPU。後兩種CPU在本篇文章中就不做展開,有興趣的同學,可以自行去研究研究。
通過研究發現,CPU的資訊基本都是在/sys/class/thermal/目錄下,通過adb shell、cat相關命令可以拿到一些手機的CPU資訊,基本步驟如下:
1、開啟終端命令視窗,如windows下的cmd程式。
2、輸入adb shell,回車。
3、輸入cat /sys/class/thermal/thermal_zone7/type,回車。其中7只是一個示例,不同的手機可能會有區別。此命令可以獲取相關的硬體類別。
4、輸入cat /sys/class/thermal/thermal_zone7/temp,回車。就可以獲取對應的溫度值。
至此,可能MTK、Qualcomm的CPU怎麼區分呢?
這裡有一個小竅門:MTK的CPU名稱類似為mtktscpu,Qualcomm的CPU名稱類似為tsens_tz_sensor。
說了這麼多,那在Android程式裡如何去實現呢? 重點來了,準備好了嗎? public static String getCpuTemp() { String temp = "Unknow"; BufferedReader br = null; FileReader fr = null; try { File dir = new File("/sys/class/thermal/"); File[] files = dir.listFiles(new FileFilter() { @Override public boolean accept(File file) { if (Pattern.matches("thermal_zone[0-9]+", file.getName())) { return true; } return false; } }); final int SIZE = files.length; String line = ""; String type = ""; for (int i = 0; i < SIZE; i++) { fr = new FileReader("/sys/class/thermal/thermal_zone" + i + "/type"); br = new BufferedReader(fr); line = br.readLine(); if (line != null) { type = line; } fr = new FileReader("/sys/class/thermal/thermal_zone" + i + "/temp"); br = new BufferedReader(fr); line = br.readLine(); if (line != null) { // MTK CPU if (type.contains("cpu")) { long temperature = Long.parseLong(line); if (temperature < 0) { temp = "Unknow"; } else { temp = (float) (temperature / 1000.0) + ""; } } else if (type.contains("tsens_tz_sensor")) { // Qualcomm CPU long temperature = Long.parseLong(line); if (temperature < 0) { temp = "Unknow"; } else if (temperature > 100){ temp = (float) (temperature / 10.0) + ""; } else { temp = temperature + ""; } } } } if (fr != null) { fr.close(); } if (br != null) { br.close(); } } catch (Exception e) { LogUtil.e(e); } finally { if (fr != null) { try { fr.close(); } catch (Exception e) { LogUtil.e(e); } } if (br != null) { try { br.close(); } catch (Exception e) { LogUtil.e(e); } } } return temp; } 這裡只是提供一個基本的思路,大家可以在此基礎上進行完善和擴充套件。 歡迎大家各抒己見,O(∩_∩)O哈哈~