Android check battery level

Before your application does much work in background, it is a good idea to check the current battery level. By doing this, you avoid the situation that the phone turns off itself before the background tasks are not completed. To achieve this goal, first you need to create an object of IntentFilter with its constructor takes the Intent.ACTION_BATTERY_CHANGED. Intent.ACTION_BATTERY_CHANGED is a system action that broadcasts a sticky Intent object. In the Intent object, there are information about battery, including the battery level. To receive this Intent, you simply call registerReceiver() method passing in null as the receiver.
To get the current battery level from the Intent object, you can call the getIntExtra() method of the Intent object passing the BatteryManager.EXTRA_LEVEL and default value (-1). To obtain the percentage of the current battery level, you have to divide it by the maximum battery level and multiply the result by 100. The maximum battery level can be accessed by passing the BatteryManager.EXTRA_SCALE to the getIntExtra() method. The example code below shows you how to register the broadcast receiver to receive the sticky Intent, get current and maximum battery levels, calculate the percentage of the current battery level, and display the result in the Toast messages.

  public class MainActivity extends ActionBarActivity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     // Create an IntentFilter object that matches battery change action
     IntentFilter filter=new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
     // Register broadcast receiver to receive a sticky intent
     Intent intent=this.registerReceiver(null, filter);
     // Get the current battery level
     int curlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
     int maxlevel = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
     float batteryPercent = (curlevel / (float)maxlevel)*100;
     if(batteryPercent<20){
       Toast.makeText(this, "The battery("+batteryPercent+"%) is low.", Toast.LENGTH_LONG).show();
     }
     else{
     Toast.makeText(this, "The battery("+batteryPercent+"%) is ok.", Toast.LENGTH_LONG).show();

}
   }

}

Android-check-battery-level

Posted by: Dara | post date: 10-06-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.