Determine whether the current Activity is a required Activity

Keywords: Android

1. Get the current Activity instance through topActivity of RunningTaskInfo. The Activity obtained in this way can only ensure that it has executed the Activity.onCreate method, but not the Activity.onResume method. This method has been banned since api 21 and should be used with caution.

    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. Monitor the current Activity instance through the ActivityLifecycleCallbacks interface provided after Android 4.0, which can be obtained from onActivityCreated or onActivityResumed. It is recommended to obtain it in onActivityResumed, and it is better to hold it in the way of soft reference or weak reference to prevent OOM.

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 = RuijieApplication
                .getCurrentActivityRef();

        if (currentActivityRef == null) {
            return false;
        }

        Activity currentActivity = currentActivityRef.get();
        if (currentActivity == null || !clazz.isInstance(currentActivity)) {
            return false;
        }

        return true;
    }

3. For handwritten Activity management Stack, you can use Stack or List to store activities that have executed Activity.onCreate or Activity.onResume methods, and remove them from Activity.onPause or Activity.onDestroy accordingly.

4. Reflection mode

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;
}

Posted by nomanoma on Tue, 05 May 2020 00:58:29 -0700