Created
May 17, 2019 14:53
-
-
Save savasadar/a7d5f6318883081c1011d86dc9a0856b to your computer and use it in GitHub Desktop.
Get current foreground activity context in android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't know, This gist created 2 years ago. If you try on Android 9, please let me know.