How to open dynamic links using Firebase notifications?

前端 未结 1 1948
予麋鹿
予麋鹿 2021-02-10 05:11

I am trying to implement Firebase notifications for our android app.

I have also implemented Dynamic Links in the app.

But, I am not able to figure out a way to

1条回答
  •  醉梦人生
    2021-02-10 05:45

    You will have to implement a server side sending of the notification with a custom data as currently the console doesn't support it. (Using the custom key-value pairs wont work either as when your app is in background mode the notification wont deep link). Read more here: https://firebase.google.com/docs/cloud-messaging/server

    Once you have your own App Server, you can then include the Deep Link URL into the custom data section of the notification.

    In your FirebaseMessagingService implementation you will need to look at the payload and take the URL from there, create a custom intent that uses that Deep Link URL.

    I am currently using AirBnb's deep link dispatcher library (https://github.com/airbnb/DeepLinkDispatch) that works quite well in this situation as you can set the data and the link to the DeepLinkActivity and that will do the link processing for you. In the below example, I convert the payload from the server into an object called DeepLinkNotification and this contains a URL field.

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

    In doing this implementation, you also won't open any links you cant handle compared to if you just set the intent to Intent.ACTION_VIEW with any URL.

    0 讨论(0)
提交回复
热议问题