开发者

Disable/enable BroadcastReceiver when battery low/okay

I am working on an app that uses an alarm to do something periodically. The alarm is set when the phone has completed booting. The BroadcastReceiver receiving the alarm and starting a service gets disabled when battery goes low and enabled when battery is okay again:

@Override
public void onReceive(final Context context, final Intent intent) {
    if (intent != null && intent.getAction() != null) {
        String action = intent.ge开发者_运维百科tAction();
        if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
            // Set alarm
        } else if (action.equals(Intent.ACTION_BATTERY_LOW)) {
            setLocationAlarmReceiverEnabled(context, false);
        } else if (action.equals(Intent.ACTION_BATTERY_OKAY)) {
            setLocationAlarmReceiverEnabled(context, true);
        }
    }
}

private void setLocationAlarmReceiverEnabled(final Context context,
        final boolean enabled) {
    PackageManager packageManager = context.getPackageManager();
    ComponentName locationAlarmReceiver = new ComponentName(context,
            LocationAlarmReceiver.class);
    packageManager.setComponentEnabledSetting(locationAlarmReceiver,
        enabled ? PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
                : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
        PackageManager.DONT_KILL_APP);
}

In a practical test I could confirm that the BroadcastReceiver"LocationAlarmReceiver" gets disabled when battery level goes down to 15% and, after the phone was connected to AC/USB, it gets enabled again when the battery level went up to 30%.

But now I have had the following scenario:

  1. Battery level goes down to 15%, "LocationAlarmReceiver" gets disabled
  2. Phone eventually turns itself off because battery is exhausted
  3. Phone is connected to AC/USB
  4. Phone is switched on and boots, continues to charge, battery level reaches 100%
  5. "LocationAlarmReceiver" is still disabled

I can only guess that the Intent.ACTION_BATTERY_OKAY intent was never delivered.

Is this observation correct? How can I make sure that the "LocationAlarmReceiver" gets enabled again?


If you are not getting the call on Intent.ACTION_BATTERY_OKAY then you should enable the receiver when you get the call in ACTION_BOOT_COMPLETED check if your receiver is disabled then you should enable it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜