Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how get current CPU temperature programmatically in all Android Versions?

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;
  }

and use it like it :

float cpu_temp = getCurrentCPUTemperature();
txtCpuTemp.setText(cpu_temp + " " + (char) 0x00B0 + "C");

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 :

57.0 in android 6 and under (6,5,4)

57000.0 in android 7 and above (7,8,9)

I try this code too :

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

but do not work :(

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

UPDATE:

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");
    }
like image 350
Sana Ebadi Avatar asked Mar 31 '19 12:03

Sana Ebadi


1 Answers

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;
}

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

like image 99
Martin Zeitler Avatar answered Sep 28 '22 23:09

Martin Zeitler