Search code examples
androidnotificationspush-notificationgoogle-cloud-messagingwakelock

Should I call WakeLock before creating a notification?


I'm adding notifications to an Android app and only have the emulator to test with at the moment. When a notification is received, my onMessage() method in my GCMBaseIntentService subclass (GCMIntentService) is called. From here I create a notification to appear. If I turn the emulator on standby, no notification is seen (I do t know if it would be heard on a device?). So should I be calling WakeLock to wake the device before creating the notification?

Thanks


Solution

  • I'm not sure if the emulator being in standby is equivalent to a locked device. If it is, you should definitely call WakeLock in order for the notification to appear even when the device is locked.

    Here's sample code :

    @Override
    protected void onMessage(Context context, Intent intent) {
        // Extract the payload from the message
        Bundle extras = intent.getExtras();
        if (extras != null) {
            String message = (String) extras.get("payload");
            String title = (String) extras.get("title");
    
            // add a notification to status bar
            NotificationManager mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            Intent myIntent = new Intent(this,MyActivity.class);
            Notification notification = new Notification(R.drawable.coupon_notification, title, System.currentTimeMillis());
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification);
            contentView.setImageViewResource(R.id.image, R.drawable.gcm_notification);
            contentView.setTextViewText(R.id.title, title);
            contentView.setTextViewText(R.id.text, message);
            notification.contentView = contentView;
            notification.contentIntent = PendingIntent.getActivity(this.getBaseContext(), 0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            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);
        }
    }
    

    Of course you'll need to add this permission to your manifest :

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