Tuesday, March 29, 2011

Getting Battery Information on Android

Getting the Battery Information in Android without Apps like AnyCut, Power Manager or System Monitor is one of the hardest task. You can try those if you have an Android phone, anyway here is how to get the Battery Information (some of the codes are undocumented).

public class Main extends Activity {

  private TextView contentTxt;

  private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){

    @Override

    public void onReceive(Context arg0, Intent intent) {


      // TODO Auto-generated method stub

      int level = intent.getIntExtra("level", 0);

      contentTxt.setText(String.valueOf(level) + "%");

    }


  };



  @Override

  public void onCreate(Bundle icicle) {

    super.onCreate(icicle);

    setContentView(R.layout.main);


    contentTxt = (TextView) this.findViewById(R.id.monospaceTxt);

    this.registerReceiver(this.mBatInfoReceiver,

    new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

  }

}




Quick Explanation

Here we listen to a Intent (ACTION_BATTERY_CHANGED) and register a receiver when the intent is fired. In ActionScript, this is i believe is DispatchEvent, and we would call mBatInfoReceiver and get the current level of our battery life and put that int value to our textfield or TextView.

3 comments:

  1. There are the Android application development firms have developed much battery managing apps like Battery Info,Battery, but without using any apps checking the level of battery in percentage is most interesting and agile thing for developers.

    ReplyDelete
  2. Nice it seems to be good post... It will get readers engagement on the article since readers engagement plays an vital role in every blog.i am expecting more updated posts from your hands.
    iOS App Development Company
    Android App Development Company

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete