Thursday, November 29, 2012

Battery Info in android.

Here is example for how to get Battery information in android.

Example:

Code for xml file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >


    <TextView
        android:id="@+id/txtinfo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />


</LinearLayout>

Code for Java file.

public class MainActivity extends Activity {
 private TextView batteryinfo;
 private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context arg0, Intent intent) {
   // TODO Auto-generated method stub
   int level = intent.getIntExtra("level", 0);
   batteryinfo.setText(String.valueOf(level) + "%");
  }
 };

 @Override
 public void onCreate(Bundle icicle) {
  super.onCreate(icicle);
  setContentView(R.layout.activity_main);
  batteryinfo = (TextView) this.findViewById(R.id.txtinfo);
  this.registerReceiver(this.batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
 }
}

No comments:

Post a Comment