How to stack Firebase Cloud Messaging notifications when the application is not running?

前端 未结 3 519
梦如初夏
梦如初夏 2020-12-03 09:07

I am using Firebase Cloud Messaging to send push notifications from my server to my android application.

When the application is running, the notificat

3条回答
  •  情歌与酒
    2020-12-03 09:55

    Firebase will not call your onMessageReceived when your app is in the background or killed, and you can't customise your notification. System generated notification will show.

    to make Firebase library to call your onMessageReceived in every case

    a) Foreground

    b) Background

    c) Killed

    you must not put JSON key "notification" in your request to firebase API but instead use "data", see below.

    For example, following message will not call onMessageReceived()

    {
      "to": "/topics/test",
      "notification": {
        "title" : "title",
        "message": "data!"
       }
    }
    

    but this will work

    {
      "to": "/topics/test",
       "data": {
           "title":"title",
           "message":"data!"
       }
    } 
    

    see this it has a detailed description of firebase message type For example:

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
    
        Log.d(TAG, "From: " + remoteMessage.getFrom());
    
        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            sendNotification(remoteMessage.getData().get("message").toString(), remoteMessage.getData().get("title").toString());
        }
    
    }
    
    private void sendNotification(String message, String title) {
            int requestID = (int) System.currentTimeMillis();
            Intent intent = new Intent(this, activityCompat);
    
            PendingIntent pendingIntent = PendingIntent.getActivity(this, requestID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.small_logo)
                    .setContentTitle(title)
                    .setContentText(message).setContentIntent(pendingIntent)
                    .setAutoCancel(true)
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText(messageBody))
                    .setTicker(messageBody);
    
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
            Notification notification = notificationBuilder.build();
    
            notificationManager.notify(0, notification);
    
    }
    

提交回复
热议问题