我正在使用Firebase并测试在应用程序处于后台时从服务器发送通知到我的应用程序。通知发送成功,它甚至出现在设备的通知中心,但当通知出现或即使我点击它,我的FCMessagingService中的onmessagerreceived方法永远不会被调用。

当我测试这个,而我的应用程序是在前台,onmessagerreceived方法被调用,一切工作正常。问题发生在应用程序在后台运行时。

这是我有意为之的行为吗,或者我有办法解决这个问题吗?

这是我的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"));
        }
    }
}

当前回答

默认情况下,当你的应用程序在后台,你点击通知时,你的应用程序中的启动器活动将被启动,如果你的通知有任何数据部分,你可以在相同的活动中处理它,如下所示。

if(getIntent().getExtras()! = null){
  //do your stuff
}else{
  //do that you normally do
}

其他回答

消息有两种类型:通知消息和数据消息。 如果你只发送数据消息,那就是在你的消息字符串中没有通知对象。它会在应用程序在后台时被调用。

这个方法handleIntent()已经被贬低了,所以处理通知可以如下所示:

前台状态:点击通知将转到你在创建通知时提供的pending Intent的活动,因为它通常是用通知的数据负载创建的。 后台/已终止状态——在这里,系统本身根据通知有效负载创建了一个通知,点击该通知将带你到应用程序的启动器活动,在那里你可以轻松地获取任何生命周期方法中的Intent数据。

默认情况下,当你的应用程序在后台,你点击通知时,你的应用程序中的启动器活动将被启动,如果你的通知有任何数据部分,你可以在相同的活动中处理它,如下所示。

if(getIntent().getExtras()! = null){
  //do your stuff
}else{
  //do that you normally do
}

我也有类似的问题。根据本页中提到的答案和参考资料,以下是我如何用以下方法解决问题的两点意见:

我之前的消息格式如下:

    {
  "notification": {
    "title": "AppName",
    "sound": null,
    "body": "Hey!YouhaveaMessage"
  },
  "data": {
    "param1": null,
    "param2": [
      238
    ],
    "id": 1
  },
  "to": "--the device push token here--"
}

我修改了消息格式如下:

    {
  "data": {
    "title": "AppName",
    "body": "Hey! You have a message",
    "param1": null,
    "param2": [
      238
    ],
    "id": 1
  },
  "priority": "high",
  "to": " — device push token here — "
}

然后我从“data”负载本身检索标题、主体和所有参数。这解决了问题,然后我可以得到onmessagerreceived回调,即使应用程序是在后台。 我写了一篇博客文章解释了同样的问题,你可以在这里找到。

在MainActivity的onCreate方法中调用这个:

if (getIntent().getExtras() != null) {
           // Call your NotificationActivity here..
            Intent intent = new Intent(MainActivity.this, NotificationActivity.class);
            startActivity(intent);
        }