BroadcastReceiver not called when screen locked in Android

ぃ、小莉子 提交于 2019-11-28 08:44:54

问题


In my Application, when a notification arrives, the BroadcastReceiver is not called if the screen is locked. But when screen is unlocked, the BroadcastReceiver is called and displays the notification.

I also put the following permission in my manifest:

android.permission.WAKE_LOCK

But still not working.


回答1:


Here's the code that works for me:

NotificationManager mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(...);
...
mManager.notify(0, notification);
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
wl.acquire(15000);

Make sure that you send the notification from your server with delay_while_idle=0 (that's the default value), or the notification won't be sent by GCM until your device wakes up.




回答2:


Open the Activity A which you want to start from onReceive(....) of BroadCastReceiver. Paste this in onCreate() of Activity A

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

Make sure you are not pasting it before setContentView(....) :-)



来源:https://stackoverflow.com/questions/18481641/broadcastreceiver-not-called-when-screen-locked-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!