Firebase onMessageReceived not called when app in

2018-12-31 09:34发布

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 appears on the notification centre of the device, but when the notification appears or even if I click on it, the onMessageReceived method inside my FCMessagingService is never called.

When I tested this while my app was in the foreground, the onMessageReceived method was called and everything worked fine. The problem occurs when the app is running in the background.

Is this intended behaviour, or is there a way I can fix this?

Here is my FBMessagingService:

import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class FBMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.i("PVL", "MESSAGE RECEIVED!!");
        if (remoteMessage.getNotification().getBody() != null) {
            Log.i("PVL", "RECEIVED MESSAGE: " + remoteMessage.getNotification().getBody());
        } else {
            Log.i("PVL", "RECEIVED MESSAGE: " + remoteMessage.getData().get("message"));
        }
    }
}

23条回答
琉璃瓶的回忆
2楼-- · 2018-12-31 09:58

DEPRECATED SOLUTION:

I have a perfect solution for this:

You need to perform 2 simple steps:

  1. Upgrade your firebase to version compile com.google.firebase:firebase-messaging:10.2.1
  2. Override handleIntent(Intent intent) method in your FirebaseMessagingService class.

handleIntent() method is called everytime whether app is in foreground, background or killed state.

查看更多
无色无味的生活
3楼-- · 2018-12-31 10:00

If app is in background Fire-base by default handling notification But if we want to our custom notification than we have to change our server side, which is responsible for to send our custom data(data payload)

Remove notification payload completely from your server request. Send only Data and handle it in onMessageReceived() otherwise your onMessageReceived will not be triggered when app is in background or killed.

now,your server side code format look like,

{
  "collapse_key": "CHAT_MESSAGE_CONTACT",
  "data": {
    "loc_key": "CHAT_MESSAGE_CONTACT",
    "loc_args": ["John Doe", "Contact Exchange"],
    "text": "John Doe shared a contact in the group Contact Exchange",
    "custom": {
      "chat_id": 241233,
      "msg_id": 123
    },
    "badge": 1,
    "sound": "sound1.mp3",
    "mute": true
  }
}

NOTE: see this line in above code
"text": "John Doe shared a contact in the group Contact Exchange" in Data payload you should use "text" parameter instead of "body" or "message" parameters for message description or whatever you want to use text.

onMessageReceived()

@Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e(TAG, "From: " + remoteMessage.getData().toString());

        if (remoteMessage == null)
            return;

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
           /* Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());*/
            Log.e(TAG, "Data Payload: " + remoteMessage);

            try {

                Map<String, String> params = remoteMessage.getData();
                JSONObject json = new JSONObject(params);
                Log.e("JSON_OBJECT", json.toString());


                Log.e(TAG, "onMessageReceived: " + json.toString());

                handleDataMessage(json);
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
        }
    }
查看更多
像晚风撩人
4楼-- · 2018-12-31 10:01

I have implemented this easy way to send messages even if the app is closed, background and in foreground too. I was previously using firebase console but I get only messages, not images and custom data.

To send this custom data with image you can use a tool called AdvancedREST Client, it's a chrome extension, and send a message with the following parameters:

Rest client tool Link: https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo

use this url:- https://fcm.googleapis.com/fcm/send Content-Type:application/json Authorization:key=Your Server key From or Authorization key(see below ref)

{ "data": 
  { "image": "https://static.pexels.com/photos/4825/red-love-romantic-flowers.jpg", 
    "message": "Firebase Push Message Using API" 
    "AnotherActivity": "True" 
  }, 
  "to" : "device id Or Device token" 
}

Authorization key can be obtained by visiting Google developers console and click on Credentials button on the left menu for your project. Among the API keys listed, the server key will be your authorization key.

And you need to put tokenID of the receiver in the to section of your POST request sent using API.

And This piece of android code //message will contain the Push Message

String message = remoteMessage.getData().get("message1");

//imageUri will contain URL of the image to be displayed with Notification
String imageUri = remoteMessage.getData().get("image");

//If the key AnotherActivity has  value as True then when the user taps on notification, in the app AnotherActivity will be opened.
//If the key AnotherActivity has  value as False then when the user taps on notification, in the app MainActivity2 will be opened.
String TrueOrFlase = remoteMessage.getData().get("AnotherActivity");

//To get a Bitmap image from the URL received
bitmap = getBitmapfromUrl(imageUri);

sendNotification(message, bitmap, TrueOrFlase);
查看更多
步步皆殇っ
5楼-- · 2018-12-31 10:02

This is working as intended, notification messages are delivered to your onMessageReceived callback only when your app is in the foreground. If your app is in the background or closed then a notification message is shown in the notification center, and any data from that message is passed to the intent that is launched as a result of the user tapping on the notification.

You can specify a click_action to indicate the intent that should be launched when the notification is tapped by the user. The main activity is used if no click_action is specified.

When the intent is launched you can use the

getIntent().getExtras();

to retrieve a Set that would include any data sent along with the notification message.

For more on notification message see docs.

查看更多
后来的你喜欢了谁
6楼-- · 2018-12-31 10:02

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);
        }
查看更多
登录 后发表回答