Android
Foreground Activity
Context
Mobile Development
Android Programming

How to get current foreground activity context in android?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In Android, there is no magical global API that safely returns “the current foreground activity” at any moment from anywhere in your app. If you need that information, the usual approach is to track activity lifecycle events yourself and keep a weak reference to the activity that is currently resumed.

That solution works, but it should be used carefully. Reaching for the current activity from unrelated code is often a design smell, and storing a strong reference can easily create leaks.

Activity Context Versus Application Context

Before solving the tracking problem, it is important to distinguish the two common context types:

  • application context lives as long as the app process
  • activity context is tied to one activity and is needed for many UI operations

If all you need is access to resources, preferences, or a long-lived service object, application context is usually enough. You only need the current activity context for work that is specifically attached to the active UI, such as showing a dialog or requesting a permission.

Track The Foreground Activity In Application

A common pattern is to register Application.ActivityLifecycleCallbacks and update a weak reference when an activity is resumed.

kotlin
1import android.app.Activity
2import android.app.Application
3import android.os.Bundle
4import java.lang.ref.WeakReference
5
6class MyApp : Application(), Application.ActivityLifecycleCallbacks {
7    private var currentActivityRef: WeakReference<Activity>? = null
8
9    override fun onCreate() {
10        super.onCreate()
11        registerActivityLifecycleCallbacks(this)
12    }
13
14    fun currentActivity(): Activity? = currentActivityRef?.get()
15
16    override fun onActivityResumed(activity: Activity) {
17        currentActivityRef = WeakReference(activity)
18    }
19
20    override fun onActivityPaused(activity: Activity) {
21        if (currentActivityRef?.get() === activity) {
22            currentActivityRef = null
23        }
24    }
25
26    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
27    override fun onActivityStarted(activity: Activity) {}
28    override fun onActivityStopped(activity: Activity) {}
29    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
30    override fun onActivityDestroyed(activity: Activity) {}
31}

Then declare the custom application class in AndroidManifest.xml.

Using The Tracked Activity

Once the application object tracks the resumed activity, other app code can request it when absolutely necessary.

kotlin
1val app = applicationContext as MyApp
2val activity = app.currentActivity()
3
4activity?.runOnUiThread {
5    // Safe place for UI work tied to the visible activity
6}

The null check matters. There are moments when no activity is resumed, such as app startup transitions, background state, or configuration changes.

Why A Weak Reference Matters

Holding a strong reference to an activity outside its lifecycle is a classic leak pattern. An activity contains views, fragments, and potentially large resources. If some singleton stores it strongly, the garbage collector cannot free it after rotation or navigation.

A WeakReference allows the activity to be collected normally. That makes it the right default for this tracking pattern.

Prefer Passing Context Explicitly When You Can

Although tracking the foreground activity is possible, it is often better to pass the needed activity or context down through the code that actually owns the UI interaction.

For example, this is usually better than asking a singleton to discover the active screen:

kotlin
1class PermissionCoordinator {
2    fun requestCamera(activity: Activity) {
3        // launch permission request from the activity that owns the flow
4    }
5}

This keeps lifecycle ownership explicit and reduces surprising behavior.

Foreground Does Not Always Mean Safe To Use

Even if you have a reference to the resumed activity, you still need to care about thread and lifecycle timing. By the time background work finishes, that activity might be finishing, destroyed, or replaced by another one.

Check isFinishing or isDestroyed when appropriate, and perform UI work on the main thread.

Common Pitfalls

  • Storing the activity in a singleton with a strong reference and leaking it.
  • Using activity context where application context would have been enough.
  • Assuming there is always exactly one valid foreground activity.
  • Calling UI code from a background thread after retrieving the activity.
  • Treating global current-activity access as a substitute for good lifecycle-aware design.

Summary

  • Android does not provide a universal safe getter for the current foreground activity.
  • Track it with Application.ActivityLifecycleCallbacks if you truly need it.
  • Store the activity in a WeakReference, not a strong reference.
  • Use activity context only for UI-related work that depends on the current screen.
  • Prefer explicit context passing over global lookup when architecture allows it.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.