Firebase Messaging - Create Heads-Up display when app in background

Brien Crean picture Brien Crean · Sep 25, 2016 · Viewed 8.6k times · Source

With FCM I receive push notifications in the system tray when the app is in the background or not running. When the app is in the foreground I can override onMessageReceived and create my own heads-up notification with NotificationCompat.

Is there a way to create a heads-up notification when my app is in the background or not running?

Thanks

EDIT: For reference here is the message payload I am using via curl to https://fcm.googleapis.com/fcm/send

{
  "to":"push-token",
    "content_available": true,
    "priority": "high",
    "notification": {
      "title": "Test",
      "body": "Mary sent you a message!",
      "sound": "default"
    },
    "data": {
      "message": "Mary sent you a Message!",
      "notificationKey":"userID/notification_type",
      "priority": "high",
      "sound": "default"
    }
}

Answer

Shivang picture Shivang · Nov 4, 2016

I found solution: I just remove notification tag from json sent to firebase server from our local server then I am generating callback in MyFirebaseMessagingService : onMessageReceived() method. n this method I am generating local notification using NotificationCompat.Builder class. Here is the code for android:

private void sendNotification(RemoteMessage remoteMessage) {
        Intent intent = new Intent(this, SplashActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(AppConstant.PUSH_CATEGORY, remoteMessage.getData().get("category"));
        intent.putExtra(AppConstant.PUSH_METADATA, remoteMessage.getData().get("metaData"));
        intent.putExtra(AppConstant.PUSH_ACTIVITY, remoteMessage.getData().get("activity"));
        intent.putExtra(AppConstant.PUSH_ID_KEY, remoteMessage.getData().get("_id"));

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(remoteMessage.getData().get("title"))
                .setContentText(remoteMessage.getData().get("body"))
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder.build());
    }