androidnavigationdeep-linkingandroid-jetpack-navigationandroid-navigation-graph

Using jetpack navigation, does anyone know how to check to see if a deeplink is defined in the app before trying to navigate to it?


The use case is to determine if a deeplink is routable/defined, before attempting to navigate and if it is not defined to route differently.

I came up with the following solution, but was curious if there is a more elegant/differently solution.

@SuppressLint("RestrictedApi")
fun NavController.isDeepLinkDefined(deeplink: Uri, action: String, mimeType: String): Boolean {
    return graph.matchDeepLink(NavDeepLinkRequest(deeplink, action, mimeType)) != null
}

Solution

  • You should use hasDeepLink, which is the public API for checking whether a deep link exists:

    Checks the given NavDeepLinkRequest, and determines whether it matches a NavDeepLink added to the destination by a call to addDeepLink. It returns true if the request is a valid match, and false otherwise.

    This should be called prior to NavController.navigate to ensure the deep link can be navigated to.

    When used on the root graph of the NavController, all destinations are checked for the given deep link:

    // Pass it a Uri
    navController.graph.hasDeepLink(uri)
    
    // Or a NavDeepLinkRequest
    navController.graph.hasDeepLink(deepLinkRequest)