11

I'm new with working with notifications in my app so please bear with me. I have a pending intent which will navigate to MainActivity when the user clicks on it. I want to change it so that it navigates to a fragment that has navigation arguments.

My code for pending intent

        val notifyIntent = Intent(context, MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
            data = Uri.parse(uri)
        }
        return PendingIntent.getActivity(
            context, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT
        )

Navigation action for my fragment

       NavigationGraphMainDirections.actionGlobalManagePostFragment("data")

I don't know if I have to send the string of data with the notification and get it back with the pending intent. What is the solution here?

Maryam Mirzaie
  • 536
  • 6
  • 24

2 Answers2

16

The best way to achieve what you want is to use an explicit deep link.

Create your pending intent as in:

val pendingIntent = NavDeepLinkBuilder(context)
.setGraph(R.navigation.nav_graph)
.setDestination(R.id.android)
.setArguments(args)
.createPendingIntent()
BMacedo
  • 768
  • 4
  • 10
  • 1
    how to trigger that intent ? – Evgeniy Mishustin Feb 18 '20 at 12:04
  • 1
    Add it to your Notification Builder: `NotificationCompat.Builder(...).setContentIntent(pendingIntent)` – Luke Needham Apr 24 '20 at 21:04
  • 1
    if I need to set as setGraph a nested graph? my destination is never called. How can I solve? – Carlos Dec 12 '20 at 10:56
  • I am creating a pending intent with background push notification. But as is not running so I am getting NPE in NavDeepLinkBuilder class for `android.content.pm.PackageManager android.content.Context.getPackageManager()` – xaif Feb 03 '21 at 15:31
0

First you need to create a pending Intent like this:

val pendingIntent = NavDeepLinkBuilder(context)
            .setGraph(R.navigation.your_navigation_graph_id)
            .setDestination(R.id.id_that_fragment_you_want_to_open)
            .setArguments(arg_value_if_you_have)
            .createPendingIntent()

Then use pending intent like this:

 val notification = NotificationCompat.Builder(context, CHANNEL_ID)
            .setContentIntent(pendingIntent)
            . and ...