intent ACTION_BATTERY_LOW 每十秒广播一次发射。为什么?

intent ACTION_BATTERY_LOW broadcast firing every ten seconds. Why?

我正在编写一项服务,该服务必须接受 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 中收到的。为什么会这样?我能做什么或我做错了什么? 在真实设备上测试。

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

我不知道你想完成什么,但如果你重复执行该操作,你还可以监视 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

监控电池电量