Код: Выделить всё
private static final ConcurrentHashMap type2fileMap = new ConcurrentHashMap();
private static float getDefaultPhoneTemperature() {
try {
BufferedReader reader = new BufferedReader(new FileReader("/sys/class/thermal/thermal_zone0/temp"));
String line = reader.readLine();
float cpuTemperature = Float.parseFloat(line) / 1000.0f; // 转换为摄氏度
reader.close();
return cpuTemperature;
} catch (Exception e) {
//
return 0f;
}
}
public static float getDeviceTemperatureWithSysfs() {
float temperature = 0f;
String[] cpusensors_types = {
// realme
"cpu",
"tsens_tz_sensor",
// huawei
"soc",
"system_h"
};
Map type_to_file_map = getThermalTypesMap();
for (String type : type_to_file_map.keySet()) {
// Check if the file is valid
if (!containsAny(type, cpusensors_types)) {
continue;
}
File temp = new File(type_to_file_map.get(type), "temp");
if (!isFileExistsAndCanRead(temp)) {
continue;
}
// Read the kernel file parameter
try (BufferedReader reader = new BufferedReader(new FileReader(temp))) {
temperature = Float.parseFloat(reader.readLine()) / 1000f;
if (isValidTemperature(temperature)) {
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return isValidTemperature(temperature) ? temperature : getDefaultPhoneTemperature();
}
public static Map getThermalTypesMap() {
if (!type2fileMap.isEmpty()) {
return type2fileMap;
}
File[] zones = new File("/sys/class/thermal").listFiles((dir, name) -> {
return name.startsWith("thermal_zone");
});
if (zones == null) {
return type2fileMap;
}
for (File zone : zones) {
File type = new File(zone, "type");
if (!isFileExistsAndCanRead(type)) {
continue;
}
try (BufferedReader reader = new BufferedReader(new FileReader(type))) {
type2fileMap.put(reader.readLine(), zone);
} catch (Exception e) {
e.printStackTrace();
}
}
return type2fileMap;
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... me-trouble