简体   繁体   English

唤醒锁只能使用一次

[英]Wakelock only works once

I created a Service that catches incoming notifications. 我创建了一个捕获传入通知的服务。 Whenever a whatsapp notification appears the screen should be woken up and an activity is started. 每当出现whatsapp通知时,都应唤醒屏幕并开始活动。 This works fine the first time, but then the screen just stays in sleep mode and the activity runs when I unlock the phone. 第一次可以正常运行,但是随后屏幕仅处于睡眠模式,当我解锁手机时,活动开始运行。

The Service Code: I declare the variables here: 服务代码:我在这里声明变量:

@TargetApi(26)
public class NLService extends NotificationListenerService {

    private String TAG = this.getClass().getSimpleName();
    public PowerManager pm;
    public PowerManager.WakeLock wl;

the wakelock code in the onCreate function: onCreate函数中的唤醒锁代码:

pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "callOverlay:wakeScreenNotification");

and in the onNotificationPosted function: [getting the notification content etc...] 并在onNotificationPosted函数中:[获取通知内容等...]

try {
    //wake up screen
    wl.acquire();
    //run activity
    dialogIntent.putExtra("SERVICE", "whatsapp");
    new android.os.Handler().postDelayed( new Runnable() {
        public void run() {                              
            dialogIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(dialogIntent);
         }
    }, 600);
} catch (Exception e) {
    Log.i(TAG,"ERROR: "+e);
} finally {
    wl.release();
}

inside the activity I added following code inside the onCreate function: 在活动中,我在onCreate函数中添加了以下代码:

final Window win= getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

I'm new to android development. 我是android开发的新手。 What am I missing? 我想念什么? Thanks! 谢谢!

It turns out that the flag combination 原来,标志组合

FLAG_SHOW_WHEN_LOCKED | FLAG_DISMISS_KEYGUARD | FLAG_TURN_SCREEN_ON

only takes effect (turns on the screen & dismisses the keyguard) once per Activity . 每个Activity只能生效一次(在屏幕上打开并关闭键盘锁)。 Contrary to my above comment, removing and re-applying the flags does not work. 与我上面的评论相反,删除并重新应用这些标志不起作用。

If you want the screen/wake changes to take effect a second time, you have to create a new Activity, and apply the same flags to it. 如果您希望屏幕/唤醒更改再次生效,则必须创建一个新的Activity,并对其应用相同的标志。

If the user manually changes the phone state (by moving to another Activity or by turning the screen off/locking the phone), this also causes the flags to lose their effect. 如果用户手动更改电话状态(通过移动到另一个“活动”或通过关闭屏幕/锁定电话),这也会导致标志失去作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM