Skip to content
DeveloperMemos

How to Get Context in Jetpack Compose

Jetpack Compose, LocalContext, Context1 min read

In Jetpack Compose, you can get the Context from the current composition using the LocalContext object. This object provides access to the current Context at any point in the composition hierarchy.

Using LocalContext

Here's an example of how you can use LocalContext to get the Context in a Composable function:

1@Composable
2fun MyComposable(
3 context: Context = LocalContext.current
4) {
5 // Use context here
6}

In this example, we define a context parameter for our MyComposable function with a default value of LocalContext.current. This allows us to access the current Context within the function body.

You can use the Context obtained from LocalContext just like you would use it in traditional Android development. For example, you can use it to access resources, start activities, or retrieve system services.

Keep in mind that LocalContext provides the Context associated with the current composition. If you need to access a different Context, such as the application context, you can do so using traditional methods like calling context.applicationContext.

Starting an Activity

Here's an example of how you can use a button and a context parameter to start an activity from a Composable function:

1@Composable
2fun MyComposable(
3 context: Context = LocalContext.current
4) {
5 Button(onClick = {
6 val intent = Intent(context, MyActivity::class.java)
7 context.startActivity(intent)
8 }) {
9 Text("Start Activity")
10 }
11}

In this example, we define a context parameter for our MyComposable function with a default value of LocalContext.current, create a Button with an onClick lambda that creates an Intent for the activity we want to start and then uses the startActivity() method on the context parameter to start the activity when the button is tapped.

Bonus Round: Getting the Activity Itself

There is a lot of discussion about what best practices are for Compose. I will admit using the Activity inside a Composable doesn't feel great, but it might be necessary depending on your specific use case. I know I personally had to do this in a couple of projects that I was adding Compose to incrementally that still had Activites or Fragments. Here's a code snippet from inside Accompanist that you can use to get the Activity from the Context you got using LocalContext:

1internal fun Context.findActivity(): Activity {
2 var context = this
3 while (context is ContextWrapper) {
4 if (context is Activity) return context
5 context = context.baseContext
6 }
7 throw IllegalStateException("Permissions should be called in the context of an Activity")
8}