如何在 Firebase 云消息传递 (FCM) 中使用深度链接

Posted

技术标签:

【中文标题】如何在 Firebase 云消息传递 (FCM) 中使用深度链接【英文标题】:How do I use deeplinking in Firebase Cloud Messaging (FCM) 【发布时间】:2020-12-12 21:44:08 【问题描述】:

如何在 FCM 中使用深层链接?主要目标是让用户点击来自 FCM 的通知特定页面并在应用程序中打开它。

我找不到可以插入链接的方式/位置(onelink、动态链接等)。目前,应用会在点击通知后打开最后一个活动窗口。

【问题讨论】:

【参考方案1】:

FCM中有2 types of messages:通知消息数据消息。您不能将深度链接与通知消息一起使用,因为它不会在您的应用中调用您可以做出反应的处理程序。

改为发送数据消息,并在onMessageReceived 中生成您自己的notification。看看documentation for implementing onMessageReceived

文档链接到file,其中显示了创建通知的示例,其中定义了以下方法:

    private void sendNotification(String messageBody) 
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String channelId = getString(R.string.default_notification_channel_id);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.ic_stat_ic_notification)
                        .setContentTitle(getString(R.string.fcm_message))
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) 
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    

您会注意到该示例创建了一个pendingIntent。如果要创建显式深层链接,则需要将其修改为调用 .setComponentName(DestinationActivity.class)。在Create a deep link for a destination 中有更多关于此的文档。

【讨论】:

以上是关于如何在 Firebase 云消息传递 (FCM) 中使用深度链接的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 FCM(Firebase 云消息传递)制作紧凑通知?

如何在 Xamarin.iOS 中使用 FCM(Firebase 云消息传递)发送 iOS 推送通知

如何向 FCM(Firebase 云消息传递)令牌的特定用户发送消息?

Firebase Admin SDK、FCM 云消息传递

如何将 FCM(firebase 云消息传递)与 react-native 集成

Firebase 云消息传递如何在 Android 上运行