1、创建BroadcastReceiver对象,重写onReceive()方法首先获取Action事件,当判断该事件为Intent.ACTION_BATTERY_CHANGED时,获取手机当前电量和总电量

BroadcastReceiver br=new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String s=intent.getAction();
if(Intent.ACTION_BATTERY_CHANGED.equals(s)){
level=intent.getIntExtra("level", 0);
scale=intent.getIntExtra("scale", 100);
hd.sendEmptyMessage(0);
Toast.makeText(MainActivity.this, "当前电量为:"+level*100/scale+"%", Toast.LENGTH_SHORT).show();
}
}
};

2、创建Handler对象,重写handleMessage()方法,捕捉信息编号为0的消息,更改TextView的内容

Handler hd=new Handler(){
public void handleMessage(Message msg){
switch (msg.what) {
case 0:
TextView tv=(TextView)MainActivity.this.findViewById(R.id.TextView02);
tv.setText(level*100/scale+"%");;
break;

default:
break;
}
}
};

3、在Button的点击事件中注册访问电池剩余量的系统BroadcastReceiver

registerReceiver(br, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));