How do you navigate from an Android `Service` to a...
# android
o
How do you navigate from an Android
Service
to a Navigation Component destination (fragment)?
e
I think you’ll need to create an intent that contains the desired destination id as an extra, then use it to launch or resume an
Activity
that has a Navigation Host with the desired destination in its nav graph.
o
You mean like this?:
Copy code
val pendingIntent = NavDeepLinkBuilder(context)
                     .setComponentName(YourActivity::class.java)
                     .setGraph(R.navigation.your_nav_graph)
                     .setDestination(R.id.your_destination)
                     .setArguments(bundle)
                     .createPendingIntent()
context.startActivity(pendingIntent)
e
yep
o
Ok thanks, will try it.
@Evan this doesn't work, as
startActivity()
requires an Intent, not a pending intent
e
I was thinking you’d do it more manually like this and then write custom logic in the
Activity
onCreate
or
onNewIntent
methods to interact with the
NavHost.
I was hoping the NavDeepLinkBuilder fixed that, but I guess since it only creates pending intents it can’t be used.
o
I see, but I worry that it will result in two main activities running
I could use Activity launchMode singleInstance, but apparently it prevents OnActivityResult callbacks
e
Copy code
val activityService = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val appTasks = activityService.appTasks
        if(appTasks.size<1){
            launchNewApplicationInstance()
        }else{
            appTasks.get(0).moveToFront()
        }
I’ve done this before, it seemed to work
might be tricky to pass the destination along though
i
You shouldn't be using
createPendingIntent()
- use
createTaskStackBuilder().startActivities()
Note that
NavDeepLinkBuilder
already sets the appropriate flags so you won't have a separate instance (it replaces the current instance - don't use any
launchMode
flags)
e
1️⃣ that’s awesome, Ian
i
But keep in mind that on newer versions of Android, you can't start activities from the background at all, so your initial idea probably needs to be rethought entirety. Generally, you'd post a notification and it would be up to the user to choose to open your app
e
@Ian Lake so you’d probably use the pending intent with the notification to give the user control over what happens, right? I’m still new to the navigation api.
i
Yep, that's what the
createPendingIntent()
API is for
👍 1
You can read more about starting activities from the background and the alternatives on the documentation: https://developer.android.com/guide/components/activities/background-starts
172 Views