我正在使用firebase向我的应用发送通知.我想将每台设备上收到的通知保存在本地数据库中.问题是,当应用程序在后台并收到通知时,将不会调用onMessageReceived()方法,而是根据文档将通知添加到系统托盘中.该文档还提到以下用于在应用程序处于后台时收到通知:
In these cases,the notification is delivered to the device’s system tray,and the data payload is delivered in the extras of the intent of your launcher Activity.
因此,当我尝试访问intent中的extras时,找不到通知的键.
我在MainActivity.java中的代码:
if (getIntent().getExtras() != null) { for (String key : getIntent().getExtras().keySet()) { Object value = getIntent().getExtras().get(key); Toast.makeText(this,"Key: " + key + " Value: " + value,Toast.LENGTH_LONG).show(); } }
我们从服务器发送的通知:
{ "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...","notification" : { "body" : "great match!","title" : "Portugal vs. Denmark","icon" : "myicon" } }
任何人都知道如何检索通知中的值?
解决方法
这是预期的行为(正如您在
documentation中看到的那样).如果您正在使用仅通知消息有效负载(您是),则只有在您的应用处于前台时才会调用onMessageReceived(),否则系统托盘将接收它.
在(强调我的)中提到的数据:
In these cases,and the data payload is delivered in the extras of the intent of your launcher Activity.
是数据消息有效负载(见Message Types).
{ "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...","notification" : { "body" : "great match!","icon" : "myicon" },"data": { "body" : "great match!","icon" : "myicon" } }