Android 中获取当前的 Activity

需求:获取当前的 Activity 对象,Activity 是系统创建的,一种方法:在 onCreate 的时候拿到引用,这样就得修改 onCreate 方法,还得维护一个数组去管理 Activity 的引用。第二种方法:通过反射拿到 ActivityThread 中的 mActivities 属性,进而拿到当前的 activity 对象( paused 为 false 的activity)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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 activities = null;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { // 4.4 以下使用的是 HashMap
activities = (HashMap) activitiesField.get(activityThread);
}else{ // 4.4 以上使用的是 ArrayMap
activities = (ArrayMap) activitiesField.get(activityThread);
}
for (Object activityRecord : activities.values()) {
Class activityRecordClass = activityRecord.getClass();
Field pausedField = activityRecordClass.getDeclaredField("paused"); // 找到 paused 为 false 的activity
pausedField.setAccessible(true);
if (!pausedField.getBoolean(activityRecord)) {
Field activityField = activityRecordClass.getDeclaredField("activity");
activityField.setAccessible(true);
Activity activity = (Activity) activityField.get(activityRecord);
return activity;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

文章来自: https://hanks.pub