Firebase onMessageReceived not called when app in background

前端 未结 26 2648
粉色の甜心
粉色の甜心 2020-11-22 02:32

I\'m working with Firebase and testing sending notifications to my app from my server while the app is in the background. The notification is sent successfully, it even appe

相关标签:
26条回答
  • 2020-11-22 03:18

    I was having the same issue and did some more digging on this. When the app is in the background, a notification message is sent to the system tray, BUT a data message is sent to onMessageReceived()
    See https://firebase.google.com/docs/cloud-messaging/downstream#monitor-token-generation_3
    and https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/MyFirebaseMessagingService.java

    To ensure that the message you are sending, the docs say, "Use your app server and FCM server API: Set the data key only. Can be either collapsible or non-collapsible."
    See https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages

    0 讨论(0)
  • 2020-11-22 03:18

    There are two types of messages: notification messages and data messages. If you only send data message, that is without notification object in your message string. It would be invoked when your app in background.

    0 讨论(0)
  • 2020-11-22 03:22

    this method handleIntent() has been depreciated, so handling a notification can be done as below:

    1. Foreground State: The click of the notification will go to the pending Intent's activity which you are providing while creating a notification pro-grammatically as it generally created with data payload of the notification.

    2. Background/Killed State - Here, the system itself creates a notification based on notification payload and clicking on that notification will take you to the launcher activity of the application where you can easily fetch Intent data in any of your life-cycle methods.

    0 讨论(0)
  • 2020-11-22 03:22

    onMessageReceived(RemoteMessage remoteMessage) method called based on the following cases.

    • FCM Response With notification and data block:
    {
      
    "to": "device token list",
      "notification": {
        "body": "Body of Your Notification",
        "title": "Title of Your Notification"
      },
      "data": {
        "body": "Body of Your Notification in Data",
        "title": "Title of Your Notification in Title",
        "key_1": "Value for key_1",
        "image_url": "www.abc.com/xyz.jpeg",
        "key_2": "Value for key_2"
      }
    }
    
    1. App in Foreground:

    onMessageReceived(RemoteMessage remoteMessage) called, shows LargeIcon and BigPicture in the notification bar. We can read the content from both notification and data block

    1. App in Background:

    onMessageReceived(RemoteMessage remoteMessage) not called, system tray will receive the message and read body and title from notification block and shows default message and title in the notification bar.

    • FCM Response With only data block:

    In this case, removing notification blocks from json

    {
      
    "to": "device token list",
      "data": {
        "body": "Body of Your Notification in Data",
        "title": "Title of Your Notification in Title",
        "key_1": "Value for key_1",
        "image_url": "www.abc.com/xyz.jpeg",
        "key_2": "Value for key_2"
      }
    }
    

    Solution for calling onMessageReceived()

    1. App in Foreground:

    onMessageReceived(RemoteMessage remoteMessage) called, shows LargeIcon and BigPicture in the notification bar. We can read the content from both notification and data block

    1. App in Background:

    onMessageReceived(RemoteMessage remoteMessage) called, system tray will not receive the message because of notification key is not in the response. Shows LargeIcon and BigPicture in the notification bar

    Code

     private void sendNotification(Bitmap bitmap,  String title, String 
        message, PendingIntent resultPendingIntent) {
    
        NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle();
        style.bigPicture(bitmap);
    
        Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    
        NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        String NOTIFICATION_CHANNEL_ID = mContext.getString(R.string.default_notification_channel_id);
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "channel_name", NotificationManager.IMPORTANCE_HIGH);
    
            notificationManager.createNotificationChannel(notificationChannel);
        }
        Bitmap iconLarge = BitmapFactory.decodeResource(mContext.getResources(),
                R.drawable.mdmlogo);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID)
                .setSmallIcon(R.drawable.mdmlogo)
                .setContentTitle(title)
                .setAutoCancel(true)
                .setSound(defaultSound)
                .setContentText(message)
                .setContentIntent(resultPendingIntent)
                .setStyle(style)
                .setLargeIcon(iconLarge)
                .setWhen(System.currentTimeMillis())
                .setPriority(Notification.PRIORITY_MAX)
                .setChannelId(NOTIFICATION_CHANNEL_ID);
    
    
        notificationManager.notify(1, notificationBuilder.build());
    
    
    }
    

    Reference Link:

    https://firebase.google.com/docs/cloud-messaging/android/receive

    0 讨论(0)
  • 2020-11-22 03:22

    Just call this in your MainActivity's onCreate Method :

    if (getIntent().getExtras() != null) {
               // Call your NotificationActivity here..
                Intent intent = new Intent(MainActivity.this, NotificationActivity.class);
                startActivity(intent);
            }
    
    0 讨论(0)
  • 2020-11-22 03:23

    Override the handleIntent Method of the FirebaseMessageService works for me.

    here the code in C# (Xamarin)

    public override void HandleIntent(Intent intent)
    {
        try
        {
            if (intent.Extras != null)
            {
                var builder = new RemoteMessage.Builder("MyFirebaseMessagingService");
    
                foreach (string key in intent.Extras.KeySet())
                {
                    builder.AddData(key, intent.Extras.Get(key).ToString());
                }
    
                this.OnMessageReceived(builder.Build());
            }
            else
            {
                base.HandleIntent(intent);
            }
        }
        catch (Exception)
        {
            base.HandleIntent(intent);
        }
    }
    

    and thats the Code in Java

    public void handleIntent(Intent intent)
    {
        try
        {
            if (intent.getExtras() != null)
            {
                RemoteMessage.Builder builder = new RemoteMessage.Builder("MyFirebaseMessagingService");
    
                for (String key : intent.getExtras().keySet())
                {
                    builder.addData(key, intent.getExtras().get(key).toString());
                }
    
                onMessageReceived(builder.build());
            }
            else
            {
                super.handleIntent(intent);
            }
        }
        catch (Exception e)
        {
            super.handleIntent(intent);
        }
    }
    
    0 讨论(0)
提交回复
热议问题