意图ACTION_BATTERY_LOW每十秒广播一次。为什么呢?

时间:2017-12-25 14:04:32

标签: android android-service android-broadcastreceiver

我正在撰写一项必须接受 ACTION_BATTERY_LOW 广播并做出反应的服务。我正在使用下一个代码:

public class MyService extends Service {
...
private final BroadcastReceiver batteryBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(LOG_TAG, "batteryBroadcastReceiver.onReceive()->intent="+intent.toString());
            if(intent.getAction().equals(Intent.ACTION_BATTERY_LOW))
                Log.d(LOG_TAG, "intent.getAction() == Intent.ACTION_BATTERY_LOW!");
        }
    };

public void onCreate() {
    super.onCreate();

    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_BATTERY_LOW);
    registerReceiver(batteryBroadcastReceiver,intentFilter);

    }

public void onDestroy() {
    super.onDestroy();
    unregisterReceiver(batteryBroadcastReceiver);
    }
}

当电池充电水平变低(~15%)时,Android会发送一个动作 ACTION_BATTERY_LOW ,然后每隔10秒再次发送一次,我在MyServive中收到它。为什么会这样?我能做什么或者我做错了什么? 在真实设备上测试。

1 个答案:

答案 0 :(得分:0)

发送Intent.ACTION_BATTERY_LOW的期限取决于操作系统和制造商。它会定期通知您,因此您可以随时更新信息,并且可以做出更好的决策。

我不知道你想要完成什么,但如果你重复动作,你也可以监视Intent.ACTION_BATTERY_OKAY,并有一个标志,指示是否已经完成了低电量的动作。该标志根据broadcastReceiver接收的动作改变其值,例如

public class MyService extends Service {
...
private final BroadcastReceiver batteryBroadcastReceiver = new BroadcastReceiver() {
    private bool mBatteryLowActionHasBeenMade = false;

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(LOG_TAG, "batteryBroadcastReceiver.onReceive()->intent="+intent.toString());
        if(intent.getAction().equals(Intent.ACTION_BATTERY_LOW) && !this.mBatteryLowActionHasBeenMade ) {
            Log.d(LOG_TAG, "intent.getAction() == Intent.ACTION_BATTERY_LOW!");
            this.mBatteryLowActionHasBeenMade = true;
        }

        if(intent.getAction().equals(Intent.ACTION_BATTERY_OKAY)) {
            this.mBatteryLowActionHasBeenMade = false;
        }
    }
};

public void onCreate() {
    super.onCreate();

    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_BATTERY_LOW);
    intentFilter.addAction(Intent.ACTION_BATTERY_OKAY);
    registerReceiver(batteryBroadcastReceiver,intentFilter);

}

public void onDestroy() {
    super.onDestroy();
    unregisterReceiver(batteryBroadcastReceiver);
    }
}

如果这不符合您的要求,请尝试使用Intent.ACTION_BATTERY_CHANGED

监控电池电量