新建一个Receiver用于接受ACTION_BATTERY_CHANGED广播。
private int mBatteryLevel;
private int mBatteryScale;
class BatteryReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
//判断它是否是为电量变化的Broadcast Action
if(Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())){
//获取当前电量
mBatteryLevel = intent.getIntExtra("level", 0);
//电量的总刻度
mBatteryScale = intent.getIntExtra("scale", 100);
}
}
}
在onCreate中:
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
BatteryReceiver batteryReceiver = new BatteryReceiver();
registerReceiver(batteryReceiver, intentFilter);
mBackupManager = IBackupManager.Stub.asInterface(
ServiceManager.getService(Context.BACKUP_SERVICE));
这里有一点需要注意,ACTION_BATTERY_CHANGED广播为粘性广播,所以已注册就会会调用onReceive,获取到当前的电量信息。