It's a exercise of Android App to detect battery level.

A BroadcastReceiver, myBatteryReceiver, is implemented and registered to receive ACTION_BATTERY_CHANGED, and retrieve "level" via getIntExtra() method.
main.xml
AndroidBattery.java
Download the files.
Related Article: Detect Battery Info.

A BroadcastReceiver, myBatteryReceiver, is implemented and registered to receive ACTION_BATTERY_CHANGED, and retrieve "level" via getIntExtra() method.
main.xml
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
android:id="@+id/batterylevel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Battery Level:"
/>
AndroidBattery.java
package com.exercise.AndroidBattery;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.TextView;
public class AndroidBattery extends Activity {
private TextView batteryLevel;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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) + " %");
}
};
}
Related Article: Detect Battery Info.