如何使用Firebase通知打开动态链接?

7

我正在尝试为我们的安卓应用实现Firebase通知。

我还在应用中实现了动态链接。

但是,我无法找到一种方法来发送带有动态链接的通知(这样点击通知时会打开某个特定的动态链接)。我只能看到发送文本通知的选项。

是否有任何解决方法或者这是FCM的限制?

1个回答

16
您需要实现服务器端发送通知和自定义数据,因为当前控制台不支持此功能。(使用自定义键值对也行不通,因为当您的应用程序处于后台模式时,通知将不会进行深层链接)。在这里阅读更多信息:https://firebase.google.com/docs/cloud-messaging/server 一旦您拥有自己的应用服务器,您就可以将深度链接URL包含到通知的自定义数据部分中。
在您的FirebaseMessagingService实现中,您需要查看有效载荷并从那里获取URL,创建一个使用该Deep Link URL的自定义意图。
我目前正在使用AirBnb的深度链接调度程序库(https://github.com/airbnb/DeepLinkDispatch),它在这种情况下非常好用,因为您可以设置数据和链接到DeepLinkActivity,它将为您处理链接处理。在下面的示例中,我将服务器中的有效负载转换为名为DeepLinkNotification的对象,其中包含一个URL字段。
private void sendDeepLinkNotification(final DeepLinkNotification notification) {
    ...
    Intent mainIntent = new Intent(this, DeepLinkActivity.class);
    mainIntent.setAction(Intent.ACTION_VIEW);
    mainIntent.setData(Uri.parse(notification.getUrl()));
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addNextIntent(mainIntent);
    PendingIntent pendingIntent = stackBuilder.getPendingIntent(notificationId, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder = buildBasicNotification(notification);
    builder.setContentIntent(pendingIntent);

    notificationManager.notify(notificationId, builder.build());
}

DeepLinkActivity:

@DeepLinkHandler
public class DeepLinkActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dispatch();    
    }

    private void dispatch() {
        DeepLinkResult deepLinkResult = DeepLinkDelegate.dispatchFrom(this);
        if (!deepLinkResult.isSuccessful()) {
            Timber.i("Deep link unsuccessful: %s", deepLinkResult.error());
            //do something here to handle links you don't know what to do with
        }
        finish();
    }
}

在进行这个实现时,与仅将意图设置为 Intent.ACTION_VIEW 并使用任何URL相比,您也不会打开任何无法处理的链接。

谢谢,我们在我们公司就是这样使用的。 - PedroAGSantos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接