简体   繁体   中英

BroadcastReceiver not called when screen locked in Android

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.

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.

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(....) :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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