Android 电量监控

获取初始电量

Android系统发送的电量广播是一个sticky broadcast,所以可以通过给registerReceiver传递一个null参数来获取上次系统发送的电量广播。

private int getLastBatteryLevel() {
        Intent batteryIntent = registerReceiver(null, new IntentFilter(
            Intent.ACTION_BATTERY_CHANGED));
            return batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    }

监控电量

mBatteryReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                final int level = intent.getIntExtra(
                        BatteryManager.EXTRA_LEVEL, -1);

                Runnable updateBatteryLevel = new Runnable() {

                    @Override
                    public void run() {
                        setBatteryLevel(level);
                    }
                };
                mHandle.post(updateBatteryLevel);
            }
        };

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