Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Monitoring the Battery Level of an Android Device

Published? true
FormatLanguage: WikiFormat

Problem:

Your long-running application needs a means of detecting the battery level for notifying the user when the battery level goes below a certain threshold.

Solution:

A BroadcastReceiver to receive the broadcast message sent when battery status changes can identify the battery level and can be used for issuing alerts to the user.

Discussion:

Sometimes we need to show an alert to the user when the battery level of the device goes below a certain limit. The following code sets the broadcast message to be sent whenever the battery level changes and creates a broadcast receiver to receive the broadcast message which can alert the user when battery gets discharged below a certain level.

public class MainActivity extends Activity {

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
  
     /**This registers the receiver for a broadcast message 
      *to be sent when the battery level is changed*/
    
     this.registerReceiver(this.myBatteryReceiver,
       new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

     /**Intent.ACTION_BATTERY_CHANGED can be replaced with 
      * Intent.ACTION_BATTERY_LOW for broadcasting 
      * a message only when battery level is low rather than 
      * sending a broadcast message every time battery level changes*/
 }

 private BroadcastReceiver myBatteryReceiver = new BroadcastReceiver(){

 @Override
 public void onReceive(Context arg0, Intent arg1) {
  int bLevel = arg1.getIntExtra("level", 0); // gets the battery level
  Log.i("Level", ""+bLevel);
  // Here you do something useful with the battery level...
 } 
 };
}

Using this approach can prevent the user facing the situation of having to discontinue using your application due to low battery, or of having the phone suspend itself until they reach a charger.