How I get CPU usage and temperature information into an android app?

后端 未结 3 944
既然无缘
既然无缘 2020-12-18 09:26

I\'m developing an application and I don\'t know how can I get CPU usage and temperature, example in a textview. I try with TYPE_AMBIENT_TEMPERATURE to get temp

3条回答
  •  再見小時候
    2020-12-18 10:04

    for the CPU frequency you can use

    public static int[] getCPUFrequencyCurrent() throws Exception {
        int[] output = new int[getNumCores()];
        for(int i=0;i

    you might want to use this one too:

    public static int getNumCores() {
        //Private Class to display only CPU devices in the directory listing
        class CpuFilter implements FileFilter {
            @Override
            public boolean accept(File pathname) {
                //Check if filename is "cpu", followed by a single digit number
                if(Pattern.matches("cpu[0-9]+", pathname.getName())) {
                    return true;
                }
                return false;
            }
        }
    
        try {
            //Get directory containing CPU info
            File dir = new File("/sys/devices/system/cpu/");
            //Filter to only list the devices we care about
            File[] files = dir.listFiles(new CpuFilter());
            //Return the number of cores (virtual CPU devices)
            return files.length;
        } catch(Exception e) {
            //Default to return 1 core
            return 1;
        }
    }
    

    for the temperature (https://stackoverflow.com/a/11931903/1031297)

    public class TempSensorActivity extends Activity, implements SensorEventListener {
     private final SensorManager mSensorManager;
     private final Sensor mTempSensor;
    
     public TempSensorActivity() {
         mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
         mTempSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
     }
    
     protected void onResume() {
         super.onResume();
         mSensorManager.registerListener(this, mTempSensor, SensorManager.SENSOR_DELAY_NORMAL);
     }
    
     protected void onPause() {
         super.onPause();
         mSensorManager.unregisterListener(this);
     }
    
     public void onAccuracyChanged(Sensor sensor, int accuracy) {
     }
    
     public void onSensorChanged(SensorEvent event) {
     }
    

    PS. You first need to check if the sensor is present...If it isn't, there's nothing that can be done. I guess some of the apps lie.

    PS2. You can always reverse engineer an app to see how they display the temperature ;)

提交回复
热议问题