电池电量低/正常时禁用/启用BroadcastReceiver

问题描述 投票:0回答:1

我正在开发一个使用闹钟定期做某事的应用。手机完成启动后会设置闹钟。接收警报并启动服务的BroadcastReceiver在电池电量不足时被禁用,并在电池再次正常时启用:

@Override
public void onReceive(final Context context, final Intent intent) {
    if (intent != null && intent.getAction() != null) {
        String action = intent.getAction();
        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);
}

在实际测试中,我可以确认当电池电量降至15%时,BroadcastReceiver“LocationAlarmReceiver”被禁用,并且在手机连接到AC / USB后,当电池电量达到30%时,它会再次启用。

但现在我有以下情况:

  1. 电池电量降至15%,“LocationAlarmReceiver”被禁用
  2. 电话最终会自动关闭,因为电池电量耗尽
  3. 手机连接到AC / USB
  4. 手机开机启动,继续充电,电池电量达到100%
  5. “LocationAlarmReceiver”仍然被禁用

我只能猜测Intent.ACTION_BATTERY_OKAY的意图从未传递过。

这个观察是否正确?如何确保再次启用“LocationAlarmReceiver”?

android broadcastreceiver battery
1个回答
1
投票

如果你没有接到Intent.ACTION_BATTERY_OKAY的电话,那么你应该在ACTION_BOOT_COMPLETED接到电话时启用接收器检查你的接收器是否被禁用然后你应该启用它。

© www.soinside.com 2019 - 2024. All rights reserved.