如何处理背景和前景的firebase通知?

vis*_*pta 6 android firebase firebase-cloud-messaging

我想在后台和前台处理firebase通知消息.我将发送一条消息,其中包含来自开发人员的youtube链接,当用户点击通知栏时,它必须指示用户打开链接.有谁知道它是如何完成的?

 public void onMessageReceived(RemoteMessage remoteMessage) {
    // [START_EXCLUDE]
    // There are two types of messages data messages and notification messages. Data messages are handled
    // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
    // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
    // is in the foreground. When the app is in the background an automatically generated notification is displayed.
    // When the user taps on the notification they are returned to the app. Messages containing both notification
    // and data payloads are treated as notification messages. The Firebase console always sends notification

    // [END_EXCLUDE]

    // TODO(developer): Handle FCM messages here.
    // Not getting messages here? See why this may be:
    Log.d(TAG, "From: " + remoteMessage.getFrom());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.
}
Run Code Online (Sandbox Code Playgroud)

接下来要做什么来实现我的目标?提前致谢:)

dru*_*abs 5

您应该在 FCM 消息中发送数据有效负载。无论您的应用程序处于前台还是后台,数据负载都会通过消息方法接收。处理那里的行动。就像通过始终读取数据负载来显示通知一样,或者如果您想在应用程序打开时或在前台显示警报对话框。

这是一个示例有效负载:

{
  "to": "registration_id_or_topic",
  "data": {
        "message": "This is a Firebase Cloud Messaging Topic Message!",
        "youtubeURL": "https://youtu.be/A1SDBIViRtE"
   }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的 onMessageReceived 中:

public void onMessageReceived(RemoteMessage remoteMessage) {
   if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        Map<String, String> receivedMap = remoteMessage.getData();
        String youtubeURL = receivedMap.get("youtubeURL");
        showNotificationWithURLAction(youtubeURL);
   }
   .....
}
Run Code Online (Sandbox Code Playgroud)

您可以通过谷歌搜索轻松实现 showNotificationWithURLAction(...) 方法。一个样本在这里


归档时间:

查看次数:

12536 次

最近记录:

6 年,2 月 前