Android M正在监听android.os.action.DEVICE_IDLE_MODE_CHANGED [英] Android M listening to android.os.action.DEVICE_IDLE_MODE_CHANGED

查看:462
本文介绍了Android M正在监听android.os.action.DEVICE_IDLE_MODE_CHANGED的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设备进入打ze模式后,第三方应用程序可以采取措施吗?

Can a third party application get an action once the device goes in to Doze mode?

尝试注册广播接收器以进行以下操作,

Trying to register Broadcast receiver for below action,

<receiver android:name="com.doze.sample.DozemodeReceiver" android:enabled="true">
    <intent-filter>
        <action android:name=" android.os.action.DEVICE_IDLE_MODE_CHANGED" />
    </intent-filter>
</receiver>

它不起作用(未调用接收方).

It's not working (the receiver is not being called).

推荐答案

以@zmarties提供的完美答案为基础,这是完整的解决方案:

Building on a perfect answer provided by @zmarties, here is the full solution:

    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));
    }

如果您能够检查上下文何时被破坏(例如在活动或服务中),请调用此函数以避免资源泄漏:

In case you are able to check when the context is destroyed (e.g. in the activity or service), call this to avoid leaking resources:

context.unregisterReceiver(receiver);

要测试这段代码,请使用以下命令:

To test this piece of code, use the following commands:

adb shell dumpsys deviceidle force-idle

使设备进入打ze模式,

to bring the device into doze mode,

adb shell dumpsys deviceidle step

要从Doze中唤醒设备.

To wake up the device from Doze.

这篇关于Android M正在监听android.os.action.DEVICE_IDLE_MODE_CHANGED的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆