Search code examples
androidfirebasefirebase-notifications

When app in background firebase notification have notification with payload then remote message method call or not


I will try to getting data when app in background like this format

{
    "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification" : {
      "body" : "great match!",
      "title" : "Portugal vs. Denmark",
      "icon" : "myicon"
    },
    "data" : {
     "Nick" : "Mario",
     "body" : "great match!",
     "Room" : "PortugalVSDenmark"
   }
}

so data is delivered on onMessageReceived(RemoteMessage message) method or not i don't know can any one help me for this issue.


Solution

  • For notifications to be clickable when your app is in the background, you need the click_action attribute in your notification payload.

    Please check this section of the Firebase docs.

    Also, when you define the click_action attribute, you will also need a corresponding <action> attribute in the <intent-filter> of the activity that you wish to launch.

    This video explains it in quite a detailed manner.

    Though, please note that you can not set the click__action attribute if you're sending notifications from the Firebase Console. You can only do so if you send a notification from your own Admin server or using Firebase Cloud Functions.

    Lastly, in the activity that is launched, you can set additional Data using the data attribute ( also shown in the same doc that I linked above ). And when you launch your app by clicking on a notification, you can obtain the notification data using getIntent(). Check out this answer for more details on how to do that.

    For example, if your notification payload has the following structure,

    payload = {
      notification: {
        title: `You ordered a new product`,
        click_action : 'HANDLE_NOTIFICATION',
    
      },
      data : {
            product_id : 'ABC98292',
            type : `Clothes`,
            product_name : 'Cotton spring shirt'
        }
    };
    

    then, put the filter in the tag of the activity that you want to open when the notification is clicked. An example is the following :-

    <intent-filter>
        <action android:name="HANDLE_NOTIFICATION" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
    </intent-filter>
    

    Then you can get the product_id from the notification using getIntent().getStringsExtra("product_id") and so on.

    This way, you'll be opening the required activity, and can populate it with the relevant details obtained from your notification.