Friday 10 May 2013

Battery level Indicator in Android

Battery.java


public class Battery extends Activity {


private TextView batteryLevel;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_battery);
     batteryLevel = (TextView)findViewById(R.id.batterylevel);
     this.registerReceiver(this.myBatteryReceiver,
       new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
 }
 private BroadcastReceiver myBatteryReceiver= new BroadcastReceiver(){

 @Override
 public void onReceive(Context arg0, Intent arg1) {
  // TODO Auto-generated method stub
  int bLevel = arg1.getIntExtra("level", 0);

  batteryLevel.setText("Battery Level: "
    + String.valueOf(bLevel) + " %");
 }
 };
}


activity_battery.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Battery" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
      />
<TextView
 android:id="@+id/batterylevel"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Battery Level:"
 />
</RelativeLayout>



Add Battery stats permission in Manifest
<uses-permission android:name="android.permission.BATTERY_STATS"/>


Screenshot

No comments:

Post a Comment