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

时间:2017-03-16 07:19:10

标签: 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.
}

接下来要做什么来实现我的目标?在此先感谢:)

6 个答案:

答案 0 :(得分:4)

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

这是一个示例有效负载:

{
  "to": "registration_id_or_topic",
  "data": {
        "message": "This is a Firebase Cloud Messaging Topic Message!",
        "youtubeURL": "https://youtu.be/A1SDBIViRtE"
   }
}

然后在你的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);
   }
   .....
}

您可以通过Google搜索来轻松实现showNotificationWithURLAction(...)方法。一个样本是here

答案 1 :(得分:3)

这可能是this question的副本。不要发送&#34;通知&#34;在推送消息正文中。

所以基本上,我改变了推送通知请求的正文:

{
   "data": {
       "type" : "mytype"
    },
    "notification": {
        "title": "My Title",
        "body": "My Notification Message"
    },
    "to": "/topics/all"
}

要:

{
   "data": {
       "type" : "mytype",
       "title": "My Title",
       "body": "My Notification Message"
    },
    "to": "/topics/all"
}

现在我的应用程序每次都在后台调用onMessageReceived(),我只是更改了方法,以便在推送数据中使用获取的通知标题和消息。

答案 2 :(得分:0)

如果您想将用户重定向到应用中的内容而不是使用deepLink, 这里是如何在点击通知时打开链接:

Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
        notificationIntent.setData(Uri.parse(remoteMessage.getData().getString("url")); 
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
         // Resources r = getResources();
          Notification notification = new NotificationCompat.Builder(context)
                  .setTicker("yortext")
                  .setSmallIcon(android.R.drawable.ic_menu_report_image)
                  .setContentTitle("title")
                  .setContentText("content")
                  .setContentIntent(pendingIntent)
                  .build();

          NotificationManager notificationManager =  (NotificationManager) context.getSystemService(Service.NOTIFICATION_SERVICE);
          notificationManager.notify(0, notification);

要发送有效负载进入firebase控制台,创建新消息,这里您将拥有高级选项,您可以将数据放入键/值对,放入 网址如下图所示。

Adding payload to Firebase message

答案 3 :(得分:0)

android系统将始终处理有效负载中通知字段内的消息。如果您希望自己的应用处理通知,则需要将YouTube链接放在有效负载中的该数据字段中。

{ "data" : 
    { "link" : "www.youtube.com"}
}

此通知作为RemoteMessage在应用程序上收到。使用remoteMessage.getData()来获取youtube链接。

请参阅https://firebase.google.com/docs/cloud-messaging/concept-options#messages-with-both-notification-and-data-payloads

答案 4 :(得分:0)

当您的应用终止运行或后台从不触发onMessageReceive

你应该怎么办?

当推送发送时,仅在下面的示例中添加数据项; 您可以使用邮递员

  

首先需要以下网址:https://fcm.googleapis.com/fcm/send   发送时可以选择   开机自检

在添加标题后,如下所示:

  

内容类型:application / json

     

授权:key =“您的服务器密钥”

  {
        "to": "/topics/yourTopics",


        "data": {
            "title": "BlaBla",
            "body":"BlaBla"
         }
    }

如何处理;

class PushService : FirebaseMessagingService() {

     override fun onMessageReceived(remoteMessage: RemoteMessage?) {
    for (i in remoteMessage!!.data.keys) {
    //Your maps here you can do something..
    }


        val contentIntent = PendingIntent.getActivity(this,
                0, intent, PendingIntent.FLAG_UPDATE_CURRENT)

        val uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
// Your notification set here!! 
        val b = NotificationCompat.Builder(this, "1")
        val n = b.setTicker(remoteMessage!!.data["title"])
                .setWhen(0)
                .setAutoCancel(true)
                .setContentTitle(remoteMessage.data["title"])
                .setContentText(remoteMessage.data["body"])
                .setShowWhen(true)
                .setContentIntent(contentIntent)
                .setSound(uri)
                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                .setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher))
                .setStyle(NotificationCompat.BigTextStyle().bigText(remoteMessage.data["body"]))


        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            b.setSmallIcon(R.drawable.ic_push_notification_transparent)
            b.color = ContextCompat.getColor(this, R.color.colorAccent)
        } else {
            b.setSmallIcon(R.mipmap.ic_launcher)
        }

        val notificationManager = this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel("1",
                    "ic_notification",
                    NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(channel)
        }

        if (notificationManager != null) {
            notificationManager.cancel(1)
            notificationManager.notify(1, n.build())
        }
    }


}

答案 5 :(得分:0)

这是一个用 nodejs 编写的工作示例,适用于所有类型的条件处理 ForegroundBackGroundAPP Killed 这将适用于所有三个类型

let message = {
        "data": {
            "callerName": "callerName",
            "notifyType": "notifyType",
            "channelName": "channelName",
            "tragetuid": "tragetuid",
            "msg": "msg"
        },

        token: "cq4KgPelQ_ukmAL1NmNs0l:APA91bG0l2uS1djSsD181cgtgFSd8......",
    };

    let response = await admin.messaging().send(message).catch((error) => {
        console.log('Error sending message:', error);
    });
    if (!response) {
        ctx.status = 404;
        ctx.body = "Error";
    } else {
        ctx.status = 200;
        ctx.body = {
            response, message
        };
    }

所以基本上我们需要使用类型 data 而不是 notification 来获取 OnReceived() 函数中的 FCM 消息

{
        "data": {
            "callerName": "callerName",
            "notifyType": "notifyType",
            "channelName": "channelName",
            "tragetuid": "tragetuid",
            "msg": "msg"
        },

        token: "cq4KgPelQ_ukmAL1NmNs0l:APA91bG0l2uS1djSsD181cgtgFSd8......",
    }