安卓开发中获取当前Activity我们平时一般采用如下两种方式
- 通过ActivityLifecycleCallbacks接口监听当前的Activity实例,在onActivityResumed当中去获取。
- 通过管理每一个Activity的onResume方法,记录所有的activity的状态。最后调用onResume的状态的Activity即为当前activity。
但做SDK的时候Application不是我们写的,其它的activity也可能是接入方开启的,这时我们就无法通过以上方式获取。此时可以采用反射系统的Activity管理类(ActivityThread)的方式获取。代码如下。
public static Activity getCurrentActivity () {
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 = (Map) activitiesField.get(activityThread);
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);
Activity activity = (Activity) activityField.get(activityRecord);
return activity;
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}