Get temperature of battery on android

前端 未结 5 1899
再見小時候
再見小時候 2020-11-28 09:12

How do I get the temperature of the battery in android?

相关标签:
5条回答
  • 2020-11-28 09:24

    Try reading the static int BatteryManager.EXTRA_TEMPERATURE

    0 讨论(0)
  • 2020-11-28 09:26

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

    public static final String EXTRA_TEMPERATURE
    Extra for ACTION_BATTERY_CHANGED: integer containing the current battery temperature.

    0 讨论(0)
  • 2020-11-28 09:30

    Try this:

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

    then define in your Variable declarations:

    private mBatInfoReceiver myBatInfoReceiver;
    

    and in 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));
    
         } 
    

    later call e.g in a OnClickListener()

    float temp = myBatInfoReceiver.get_temp(); 
    
    String message = "Current " + BatteryManager.EXTRA_TEMPERATURE + " = " +
                      temp +  Character.toString ((char) 176) + " C";
    
    0 讨论(0)
  • 2020-11-28 09:30
        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";
        }
    
    0 讨论(0)
  • 2020-11-28 09:40
    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));
          }
    
    0 讨论(0)
提交回复
热议问题