Skip to content
DeveloperMemos

Opening Links in Compose with LocalUriHandler

Android, Compose, LocalUriHandler1 min read

Have you ever wanted to incorporate clickable links within your Jetpack Compose app? Opening links within the app itself instead of redirecting users to an external browser can greatly enhance the user experience. In this article, we will explore how to achieve this using the LocalUriHandler class.

What is LocalUriHandler?

LocalUriHandler is a class introduced in Jetpack Compose that allows you to handle and open links within your app. With LocalUriHandler, you can intercept URL intents and take control of the link navigation process. This enables you to display web content, handle deep links, or integrate any other external content without leaving your app.

Implementing LocalUriHandler in your Compose app

To get started, you need to set up the LocalUriHandler in your Compose app. Follow the steps below to integrate it effectively.

Step 1: Define a LocalUriHandler instance

First, you need to define a LocalUriHandler instance within your Composable function or ViewModel. This instance will handle the link navigation within your app.

1val localUriHandler = LocalUriHandler.current

Step 2: Use LocalUriHandler to open links

Once you have the LocalUriHandler instance, you can use it to open links within your app. The LocalUriHandler provides a openUri function, which you can call to open a specific URL.

1localUriHandler.openUri("https://www.example.com")

You can use this function wherever you want to trigger link navigation within your app. For example, you can associate it with a ClickableText or an IconButton to create clickable links.

Example usage in a Compose app

Let's see an example of how to use LocalUriHandler in a Compose app. Suppose you have a screen with clickable links that open specific URLs within your app.

1@Composable
2fun LinkScreen() {
3 val localUriHandler = LocalUriHandler.current
4
5 Column {
6 Text("Welcome to my app!")
7 ClickableText(text = "Check out our website") {
8 localUriHandler.openUri("https://www.example.com")
9 }
10 ClickableText(text = "Open the terms and conditions") {
11 localUriHandler.openUri("https://www.example.com/terms")
12 }
13 // More clickable links...
14 }
15}

In this example, the LinkScreen Composable function displays a welcome message and two clickable links. When the user clicks on either link, the corresponding URL is opened within the app using the LocalUriHandler's openUri function.

By following this approach, you can create a seamless user experience where users can navigate external content without leaving your app's context.