基于@zmarties 提供的完美答案,这里是完整的解决方案:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
BroadcastReceiver receiver = new BroadcastReceiver() {
@RequiresApi(api = Build.VERSION_CODES.M) @Override public void onReceive(Context context, Intent intent) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (pm.isDeviceIdleMode()) {
// the device is now in doze mode
} else {
// the device just woke up from doze mode
}
}
};
context.registerReceiver(receiver, new IntentFilter(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED));
}
如果您能够检查上下文何时被销毁(例如在活动或服务中),请调用它以避免泄漏资源:
context.unregisterReceiver(receiver);
要测试这段代码,请使用以下命令:
adb shell dumpsys deviceidle force-idle
使设备进入打盹模式,
adb shell dumpsys deviceidle step
从打盹唤醒设备。