唤醒锁不起作用

Wake Lock doesn't work

我正在创建闹钟并使用 WakeLock 在睡眠时唤醒 phone。

我在 Activity 中使用此代码作为唤醒锁:

public void onCreate(Bundle savedInstateState) {
    super.onCreate(savedInstateState);
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | PowerManager.ACQUIRE_CAUSES_WAKEUP, "My Wake Log");
    mWakeLock.acquire();
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN |
                    WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                    WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON,
            WindowManager.LayoutParams.FLAG_FULLSCREEN |
                    WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                    WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    setContentView(R.layout.activity_screen);
}

但是当时间到了时,我的应用程序崩溃并显示此日志猫错误:

java.lang.IllegalArgumentException: Must specify a valid wake lock level.

我已经为 AndroidManifest 添加了权限:

<uses-permission android:name="android.permission.WAKE_LOCK" />

我以为我已经指定了唤醒锁级别。我该怎么做才能解决这个问题?请帮我。谢谢

WindowManager.LaoutParams.FLAG_KEEP_SCREEN_ON 不是 PowerManager.newWakeLock() 的有效 flag/level。您很可能希望它是:

PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP.

正确的解决方法如下:使用ACQUIRE_CAUSES_WAKEUP配合PARTIAL_WAKE_LOCK唤醒设备。然后使用WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON保持屏幕亮着。 PARTIAL_WAKE_LOCK 已弃用,但仍然有效。这是一些示例代码,其中我的服务唤醒设备,启动适当的 activity,并使用唤醒锁保持设备 运行 直到 activity 有时间设置必要的标志以保持设备和屏幕开启。

         // start the activity, wake up the screen if required. This would typically
        // be done in an onReceive() method, or in my case it's when a Bluetooth device has been connected.

        PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
        final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.PARTIAL_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP), "BlueMaxService");
        wakeLock.acquire();
        Intent intent = new Intent(this, EmaxActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                wakeLock.release();
            }
        }, 10000L);

并且在 activity 中,我设置了各种标志来打开屏幕、关闭锁定屏幕和保持屏幕打开。这些标志必须尽早设置,所以最好的位置是 onAttachedToWindow()

        @Override
public void onAttachedToWindow() {
    super.onAttachedToWindow();
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
        WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
        WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
        WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
}

如果 activity 已经启动,则需要重新创建它以便设置这些标志。这可以通过在 onNewIntent()

中调用 recreate() 来完成
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    recreate();
}