在android上获取电池温度

时间:2010-10-22 13:33:58

标签: android sensor android-sensors temperature

如何在Android中获取电池的温度?

6 个答案:

答案 0 :(得分:14)

http://developer.android.com/reference/android/os/BatteryManager.html

public static final String EXTRA_TEMPERATURE
ACTION_BATTERY_CHANGED:包含当前电池温度的整数。

答案 1 :(得分:7)

试试这个:

private class mBatInfoReceiver extends BroadcastReceiver{ 

    int temp = 0;

    float get_temp(){
        return (float)(temp / 10);
    }

    @Override 
    public void onReceive(Context arg0, Intent intent) {
        temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE,0);
    }

};

然后在您的变量声明中定义:

private mBatInfoReceiver myBatInfoReceiver;

并在onCreate:

    @Override 
    public void onCreate(Bundle b) { 
        super.onCreate(b);  
        setContentView(R.layout.activity_main);

        // ...
        // Add this

        myBatInfoReceiver = new mBatInfoReceiver();                                     

        this.registerReceiver(this.myBatInfoReceiver,
                              new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

     } 

稍后在OnClickListener()

中调用
float temp = myBatInfoReceiver.get_temp(); 

String message = "Current " + BatteryManager.EXTRA_TEMPERATURE + " = " +
                  temp +  Character.toString ((char) 176) + " C";

答案 2 :(得分:6)

    public static String batteryTemperature(Context context)
    {
        Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));    
        float  temp   = ((float) intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE,0)) / 10;
        return String.valueOf(temp) + "*C";
    }

答案 3 :(得分:1)

TextView BatTemp;

private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context arg0, Intent intent) 
        {

          // TODO Auto-generated method stub

          int temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE,0);

      };

@Override
      public void onCreate(Bundle b) 
      {
        super.onCreate(b);
        setContentView(R.layout.activity_main);


        BatTemp = (TextView) this.findViewById(R.id.textView8);

        this.registerReceiver(this.mBatInfoReceiver,new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
      }

答案 4 :(得分:0)

尝试阅读static int BatteryManager.EXTRA_TEMPERATURE

答案 5 :(得分:-1)

您可以通过此功能获得CPU温度: 使用sys/class/thermal/temp命令从Android设备获取CPU温度。

public float getCpuTemp() {
    Process process;
    try {
        process = Runtime.getRuntime().exec("cat sys/class/thermal/thermal_zone0/temp");
        process.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = reader.readLine();
        float temp = Float.parseFloat(line) / 1000.0f;
        return temp;
    } catch (Exception e) {
        e.printStackTrace();
        return 0.0f;
    }
}

在我的要点中发送拉取请求:https://gist.github.com/sajadabasi/7d76379e82d51efd0a24e5829c3ce572