使用动态注册监听系统广播(电池的广播)
当电池时间改变的时候系统将发出广播,使用 下面的来注册(不能在manifest中声明)来监听到变化,做出相应的变化
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(receiver, filter);

1 public class BatteryReceiverDemo extends Activity { 2 public static final String TAG = "Battery Receiver Debug"; 3 4 TextView show = null; 5 TextView statusTV; 6 BatteryReceiver receiver = new BatteryReceiver(); 7 8 public void onCreate(Bundle bundle) { 9 super.onCreate(bundle); 10 setContentView(R.layout.battery); 11 show = (TextView) findViewById(R.id.show); 12 statusTV = (TextView) findViewById(R.id.status); 13 Log.v(TAG, "onCreate()"); 14 15 } 16 17 public void onResume() { 18 super.onResume(); 19 IntentFilter filter = new IntentFilter(); 20 filter.addAction(Intent.ACTION_BATTERY_CHANGED); 21 registerReceiver(receiver, filter); 22 Log.v(TAG, "registerReceiver OK "); 23 } 24 25 public void onPause() { 26 super.onPause(); 27 unregisterReceiver(receiver);// 解除注册广播 28 Log.v(TAG, "unregisterReceiver OK "); 29 } 30 31 public class BatteryReceiver extends BroadcastReceiver { 32 public void onReceive(Context context, Intent intent) { 33 Log.v(TAG + " Receiver", "is receive "); 34 if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) { 35 Bundle bundle = intent.getExtras(); 36 int level = bundle.getInt(BatteryManager.EXTRA_LEVEL); 37 int scale = bundle.getInt(BatteryManager.EXTRA_SCALE); 38 int status = bundle.getInt(BatteryManager.EXTRA_STATUS); 39 int health = bundle.getInt(BatteryManager.EXTRA_HEALTH); 40 int present = bundle.getInt(BatteryManager.EXTRA_PRESENT); 41 int voltage = bundle.getInt(BatteryManager.EXTRA_VOLTAGE); 42 int temperature = bundle 43 .getInt(BatteryManager.EXTRA_TEMPERATURE); 44 int technology = bundle.getInt(BatteryManager.EXTRA_TECHNOLOGY); 45 46 show.setText("level is " + level + " scale is " + scale 47 + " status is" + status + " health is " + health 48 + " persend is " + present + " voltage is " 49 + voltage + " temperature is " + temperature 50 + " technology is " + technology); 51 Log.v("receiver ", "level is " + level + " scale is " + scale 52 + " status is" + status + " health is " + health 53 + " persend is " + present + " voltage is " 54 + voltage + " temperature is " + temperature 55 + " technology is " + technology); 56 57 switch (status) { 58 case BatteryManager.BATTERY_STATUS_CHARGING: 59 Toast.makeText(context, "充电中", 4000).show(); 60 statusTV.setText("断充电中充电 BATTERY_STATUS_CHARGING "); 61 break; 62 case BatteryManager.BATTERY_STATUS_DISCHARGING: 63 statusTV.setText("断开充电 BATTERY_STATUS_DISCHARGING "); 64 break; 65 case BatteryManager.BATTERY_STATUS_FULL: 66 statusTV.setText("充电完成 BATTERY_STATUS_FULL"); 67 break; 68 case BatteryManager.BATTERY_STATUS_NOT_CHARGING: 69 statusTV.setText("没有充电 BATTERY_STATUS_NOT_CHARGING"); 70 break; 71 case BatteryManager.BATTERY_STATUS_UNKNOWN: 72 statusTV.setText("不知道状态 BATTERY_STATUS_UNKNOWN"); 73 break; 74 default: 75 break; 76 } 77 } 78 } 79 } 80 }