【问题标题】:Why is RemoteMessage.getData() returning null in firebase notifications?为什么 RemoteMessage.getData() 在 Firebase 通知中返回 null?
【发布时间】:2017-06-04 06:37:39
【问题描述】:

我正在使用 firebase 中的通知编写器通过 自定义数据 发送以下键值对:

 type : 555

我不会在通知作曲家中在 type555 周围加上双引号 ""。所以在 key 的地方我写 type 和在 value 我写 555 的地方。 以下是我检索此类型值的代码:

@Override
    public void onMessageReceived(final RemoteMessage remoteMessage) {


        final Map<String, String> data = remoteMessage.getData();
        final String type = data.get("type");
        Log.e("TAG","Type= "+type);

}

但是我得到的日志输出是:

Type= null

为什么我得到空值?如何正确检索给定键的值?

编辑 看来

final Map<String, String> data = remoteMessage.getData();

工作正常。我在这一行之后放了一个Log.e() 语句,它正确打印了 555。因此,即使存在键“type”,data.get("type") 似乎也返回 null。为什么会这样?

【问题讨论】:

  • 你能试试final String type = data.get("type").toString();吗?
  • Nirvan 怎么样?成功了吗?
  • @AL。没有。就像我在编辑中提到的那样,data.get("type") 返回 null- 所以在其上执行 toString() 只会引发 nullPointerException
  • @Al 但我最终还是修复了它。我在 strings.xml 中定义了“类型”并写了类似data.get(R.string.myType) 的内容,其中myType 是 strings.xml 中的“类型”。显然这不起作用,所以我直接写了“type”。任何想法为什么这不起作用?
  • 奇怪。如果我明天有空闲时间,我会尝试一下。同时,您能否尝试发送有效载荷via Postman or cURL 看看是否仍然相同?

标签: android firebase push-notification firebase-cloud-messaging firebase-notifications


【解决方案1】:

我遇到了同样的问题。经过一番搜索,我想出了以下解决方案。

@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    
    RemoteMessage.Notification data = remoteMessage.getNotification();
    String title = data.getTitle();
    String body = data.getBody();
    
    if (data != null){
        // do some work
    }
    
}

我试过了,它对我有用。我希望它会帮助其他人。

【讨论】:

    猜你喜欢
    • 2020-04-30
    • 1970-01-01
    • 2019-05-21
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 2022-12-26
    • 2018-01-05
    相关资源
    最近更新 更多