【问题标题】:When an app is in background, onMessageReceived method is not firing当应用程序处于后台时,onMessageReceived 方法不会触发
【发布时间】:2017-05-24 07:43:09
【问题描述】:

实际上我需要在应用程序图标中显示徽章,但我不知道如何获取徽章以及为什么当应用程序处于后台或应用程序未运行时 onMessageReceived 不调用。

public class Custom_FirebaseMessagingService extends FirebaseMessagingService          {
            private static final String TAG = "FirebaseMsgService";
            String activityName;

            @Override
            public void onMessageReceived(RemoteMessage remoteMessage) {

                if (remoteMessage == null)
                    return;
                if (remoteMessage.getNotification() != null) {
                    Log.i(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
                }
                // Check if message contains a data payload.
                if (remoteMessage.getData().size() > 0) {
                    Log.i(TAG, "Data Payload: " + remoteMessage.getData().toString());
                    try{
                        //boolean from_bg = Boolean.parseBoolean(remoteMessage.getData().get("from_bg").toString());
                        Map<String, String> data = remoteMessage.getData();
                        boolean show_fg =  Boolean.parseBoolean(data.get("show_fg"));
                        ..... 

【问题讨论】:

  • 如果你想在后台接收消息,你必须使用有效载荷数据,如firebase.google.com/docs/cloud-messaging/android/receive中所述
  • 你能说出你使用的是哪个设备吗?
  • 一直被调用 onMessageReceived (应用程序前台或后台),您只需要接收“数据”有效负载(而不是“数据”和“通知”有效负载)。如果您同时发送“数据”和“通知”有效负载,当应用程序在前台时,将调用“onMessageReceived”。
  • 我在前台发送“数据”和“通知”有效负载和 onMessageReceived,但不在后台,您对在应用图标中显示徽章有任何想法吗?

标签: android firebase firebase-cloud-messaging badge


【解决方案1】:

FCM 有两种类型

notification 消息:仅当您的应用处于前台时,发送具有此消息类型的有效负载才会触发 onMessageReceived()

data 消息:发送带有此特定消息类型的有效负载会触发onMessageReceived(),无论您的应用处于前台还是后台。

参考:https://firebase.google.com/docs/cloud-messaging/android/receive#handling_messages

【讨论】:

  • 您误用了一个术语。没有 Display 消息之类的东西,应该是 notification 消息。描述很接近,但一点也不准确。请修改它们以更准确地显示文档中显示的内容或更好,完全参考docs
  • @AL。感谢您的宝贵建议。
  • 没问题。干杯!
  • @AL 对在 facebook 等应用图标上显示徽章有任何想法吗?
【解决方案2】:

将服务添加到AndroidManifest.xml。还要确保令牌没有过期。

<service android:name=".FirebaseMessagingService">
 <intent-filter>
    <action android:name="com.google.firebase.MESSAGING_EVENT"/>
 </intent-filter>
</service>

如果令牌过期,则刷新它。

@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);

    // If you want to send messages to this application instance or
    // manage this apps subscriptions on the server side, send the
    // Instance ID token to your app server.
    sendRegistrationToServer(refreshedToken);
}

【讨论】:

  • 我已经这样做了:意图过滤器>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-29
  • 2018-06-11
  • 2018-02-20
  • 2022-09-27
  • 2020-02-10
  • 2019-07-02
  • 1970-01-01
相关资源
最近更新 更多