Search code examples
androidnotificationsandroid-notificationsandroid-jetpack-navigation

How to open Jetpack Navigation Fragment from Notification?


I'm using Jetpack Navigation in my project following image describes my navigation. In my Application Home Fragment is my NavHostFragment and I'm using foreground service in Fragment A. When I navigate from Home Fragment to Fragment A and close the application or minimize then foreground service run with notification. When I pressed notification Home fragment open but I want Fragment A would be open and all back stack would be saved. I'm using MainActivity as a PendingIntent in notification where all my navigation fragments work.

enter image description here


Solution

  • After a long time, I found the solution. In this scenario, Deeplinking will be used. And change PendingIntent from MainActivity to your destination FragmentA.

    Source Help

    nav_graph.xml

     <fragment
            android:id="@+id/fragmentA"
            android:name="com.example.FragmentA"
            android:label="Fragment A"
            tools:layout="@layout/fragment_a">
           
            <action
                .../>
            
            <deepLink
                android:id="@+id/deepLink"
                app:uri="www.example.com" />
        </fragment>
    

    AndroidManifest.xml

    <application
            ...>
            <activity
                android:name=".MainActivity"
                android:exported="true">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
                <nav-graph android:value="@navigation/nav_graph"/>
            </activity>
        </application>
    

    PendingIntent

    val pendingIntent = NavDeepLinkBuilder(context)
                    .setGraph(R.navigation.nav_graph)
                    .setDestination(R.id.fragment_a)
                    .createPendingIntent()