How do I use deeplinking in Firebase Cloud Messaging (FCM)

Viewed 241

How can I use deep linking in FCM? The main goal is for the user to click on the notification from FCM a specific page and have it open in the application.

I can't find the way/place where I can insert the link (onelink, dynamic link and etc.). Currently, the app opens the last active window after clicking on notification.

1 Answers

There are 2 types of messages in FCM: notification message and data message. You can't use deeplinking with notification messages because it doesn't call a handler in your app that you can react to.

Instead, send a data message, and in onMessageReceived, generate your own notification. Take a look at the documentation for implementing onMessageReceived.

The documentation links to a file which shows an example of creating a notification, where they define the following method:

    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());
    }

You'll notice the example creates a pendingIntent. You'll need to modify that to call .setComponentName(DestinationActivity.class) if you want to create an Explicit deep link. There's more documentation about that in Create a deep link for a destination.

Related