Skip to content

Instantly share code, notes, and snippets.

@savasadar
Created May 17, 2019 14:53
Show Gist options
  • Save savasadar/a7d5f6318883081c1011d86dc9a0856b to your computer and use it in GitHub Desktop.
Save savasadar/a7d5f6318883081c1011d86dc9a0856b to your computer and use it in GitHub Desktop.
Get current foreground activity context in android
public static Activity getActivity() {
try {
Class activityThreadClass = Class.forName("android.app.ActivityThread");
Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
activitiesField.setAccessible(true);
Map<Object, Object> activities = (Map<Object, Object>) activitiesField.get(activityThread);
if (activities == null)
return null;
for (Object activityRecord : activities.values()) {
Class activityRecordClass = activityRecord.getClass();
Field pausedField = activityRecordClass.getDeclaredField("paused");
pausedField.setAccessible(true);
if (!pausedField.getBoolean(activityRecord)) {
Field activityField = activityRecordClass.getDeclaredField("activity");
activityField.setAccessible(true);
return (Activity) activityField.get(activityRecord);
}
}
return null;
}
catch (Exception e)
{
return null;
}
}
@hamzaavvan
Copy link

Will this work in Android 9.0?

@savasadar
Copy link
Author

Will this work in Android 9.0?

I don't know, This gist created 2 years ago. If you try on Android 9, please let me know.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment