Get Battery Level in your app

I've searched and found a sample to get battery level in the screen . What is Broadcast Receivers? Broadcast Receivers is an Android implementation of system-wide publish/subscribe mechanism. The system itself broadcasts events all the time. For example, when an SMS arrives, or call comes in, or battery runs low, or system gets booted, all those events are broadcasted and any number of receivers could be triggered by them. You can also send your own broadcasts from one part of your application to another, or a totally different application. Broadcast receivers themselves do not have any visual representation nor are they actively running in memory. But when triggered, they get to execute some code, such as start an activity, a service, or something else what we defined. To know battery level , I used the following snippet in onCreate() method,


registerReceiver("put your Broadcast receiver object here", new IntentFilter(Intent.ACTION_BATTERY_CHANGED));


and in , onReceive() method ,I did the following,
public void onReceive(Context c, Intent i) {
   int level = i.getIntExtra("level", 0);
   ProgressBar pb = (ProgressBar) findViewById(R.id.progressbar);
   pb.setProgress(level);
   TextView tv = (TextView) findViewById(R.id.textfield);
   tv.setText("Battery Level: " + Integer.toString(level) + "%");
  }

 };
Full Source Code click here

Comments

Popular Posts