1. 通过RunningTaskInfo的topActivity获取当前Activity实例。通过该种方式获取的Activity,只能保证其已经执行了Activity.onCreate方法,不能保证是否执行了Activity.onResume方法。该方法在api 21以后已经被禁,使用需谨慎。
public static String getCurrentActivityName(Context context) {
ActivityManager am = (ActivityManager) context
.getSystemService(Activity.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
return componentInfo.getClassName();
}
2. 通过Android 4.0之后提供的ActivityLifecycleCallbacks接口监听当前的Activity实例,可以在onActivityCreated或者onActivityResumed当中获取到。建议在onActivityResumed当中去获取,同时最好以软引用或者弱引用的方式持有,防止OOM。(其中XxxApplication是你的工程Application)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
registerActivityLifecycleCallbacks(new ActivityLifeCycleCallbackAdapter() {
@Override
public void onActivityResumed(Activity activity) {
super.onActivityResumed(activity);
activityRef = new SoftReference<Activity>(activity);
}
});
}
public static boolean isActivityResumed(Class<?> clazz) {
if (clazz == null) {
throw new NullPointerException("activity class can not be null");
}
SoftReference<Activity> currentActivityRef = XxxApplication
.getCurrentActivityRef();
if (currentActivityRef == null) {
return false;
}
Activity currentActivity = currentActivityRef.get();
if (currentActivity == null || !clazz.isInstance(currentActivity)) {
return false;
}
return true;
}
3. 手写Activity管理栈,可以使用Stack或者List等存储已经执行了Activity.onCreate或者Activity.onResume方法的Activity,并相应在Activity.onPause或者Activity.onDestroy中移除。
4. 反射方式
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;
}