当应用在后台时,Firebase会保存数据

时间:2016-12-23 03:58:24

标签: android firebase firebase-cloud-messaging

我有一个来自服务器的示例输出,用于将通知推送到应用程序,如下所示:

  {
    "to" : "APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...",
    "notification" : {
      "body" : "great match!",
      "title" : "Portugal vs. Denmark",
      "icon" : "myicon"
    },
    "data" : {
      "Nick" : "Mario",
      "Room" : "PortugalVSDenmark"
    }
  }

当应用处于后台时,如何将内容存储在数据中,onMessageReceived仅在应用处于前台时触发。

3 个答案:

答案 0 :(得分:1)

  

根据文档,当您的应用为通知和数据付费加载消息的前台或后台时,将触发onMessageReceived()。但是,当您的应用处于后台时,通知信息将在通知栏中处理。但是,数据付费加载消息将照常接收(通过onMessageReceived())。没有问题。在此之前,您必须在客户端应用程序上实现消息处理逻辑。

check the documentation

答案 1 :(得分:1)

你可以使用getIntent()。getExtras();用于在启动以获取意图时获取意图。

更多信息here

例如:

  Bundle bundle = getIntent().getExtras();
  if (bundle != null) {
      if (bundle.containsKey("data")) {
      Intent intent = new Intent(mContext, ExpectedActivity.Class)
      intent.putExtras("PUSH_KEY",bundle.get("data").toString());
      startActivity(intent)
    }
  }

将此代码放入您的启动器活动中。即使应用程序被终止或处于后台,这也会导航您的预期活动。

你也可以尝试像这样改变你的json

{
"data" : {
"body" : "great match!",
"title": "Portugal vs. Denmark" ,
"icon  : "myicon," 
"Nick" : "Mario",
"Room" : "PortugalVSDenmark"
},
"to" : "APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx..."
}

答案 2 :(得分:0)

我找到了解决方案。从本地服务器发送到firebase服务器时,我似乎必须删除json中的notification部分。然后,如果应用程序在后台,它将触发onMessageReceived

来源:https://code.google.com/p/android/issues/detail?id=219084

所以我做的是从json中删除通知标记并手动创建我的通知。然后使用@ sunil的方法从启动器活动中检索它。

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    System.out.println("Remote Message: " + remoteMessage.toString());
    System.out.println("Token: " + FirebaseInstanceId.getInstance().getToken());
    System.out.println("From: " + remoteMessage.getFrom());
    sendNotification(remoteMessage.getData().toString());
    Log.d(TAG, "Message Data payload" + remoteMessage.getData());
}

private void sendNotification(String messageData) {
    Intent intent = new Intent(this, HomeActivity.class);
    intent.putExtra("data", messageData);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("DeliveryOptions")
            .setContentText("Test")
            .setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_SOUND)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notificationBuilder.build());
}