简短说明(Quick explanation):
通过创建BroadcastReceiver来侦测系统中有关电池Intent(ACTION_BATTERY_CHANGED)的变化,一旦有接收到相关事件,将会读取当前电量情况,并通过TextViews显示在当前屏幕。
 1 public class MyButteryDemo extends Activity {
 2     private Button button = null;
 3 
 4     @Override
 5     public void onCreate(Bundle savedInstanceState) {
 6         super.onCreate(savedInstanceState);
 7         setContentView(R.layout.main);
 8 
 9         button = (Button) findViewById(R.id.btn);
10         button.setOnClickListener(new OnClickListenerImpl());
11     }
12 
13     private class OnClickListenerImpl implements OnClickListener {
14 
15         @Override
16         public void onClick(View arg0) {
17             ButteryBroadcastReceiver receiver = new ButteryBroadcastReceiver();
18             IntentFilter filter = new IntentFilter(
19                     Intent.ACTION_BATTERY_CHANGED);
20             MyButteryDemo.this.registerReceiver(receiver, filter);
21         }
22 
23     }
24 }


 1 public class ButteryBroadcastReceiver extends BroadcastReceiver {
 2 
 3     @Override
 4     public void onReceive(Context context, Intent intent) {
 5 
 6         if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
 7             int level = intent.getIntExtra("level"0);
 8             int scale = intent.getIntExtra("scale"100);
 9             Dialog dialog = new AlertDialog.Builder(context)
10                     .setTitle("电池电量")
11                     .setMessage(
12                             "电池电量为:" + String.valueOf(level * 100 / scale)
13                                     + "%").setNegativeButton("关闭"new DialogInterface.OnClickListener() {
14                                         
15                                         @Override
16                                         public void onClick(DialogInterface dialog, int which) {
17                                             // TODO Auto-generated method stub
18                                             
19                                         }
20                                     }).create();
21             dialog.show();
22         }
23     }
24 
25 }