Android 获取activity栈中activity

方法1:


// 获取activity任务栈
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.RunningTaskInfo info = manager.getRunningTasks(1).get(0);

String packageName = info.topActivity.getPackageName();
String topclassName = info.topActivity.getClassName();  
String baseclassname = info.baseActivity.getClassName();
int acitivitynum = info.numActivities;

 方法2:

在终端或者Android Studio中的Terminal里输入命令:

adb shell dumpsys activity activities

之后可以看到如下的activity栈输出信息:

Android 获取activity栈中activity_第1张图片

 

方法3 (反射):

转自:https://www.jianshu.com/p/ac0b237bac03 

Framewok层源码中,

public final class ActivityThread {
       ......
       final ArrayMap mActivities = new ArrayMap<>();
       ......
   }

这个Map的Value是ActivityClientRecord,持有Activity对象。

Android 获取activity栈中activity_第2张图片

mLoadedApk持有ActivityThread,因此此处可以路反射过去拿到Map拿到ValueList

private static List getActivitiesByApplication(Application application) {
        List list = new ArrayList<>();
        try {
            Class applicationClass = Application.class;
            Field mLoadedApkField = applicationClass.getDeclaredField("mLoadedApk");
            mLoadedApkField.setAccessible(true);
            Object mLoadedApk = mLoadedApkField.get(application);
            Class mLoadedApkClass = mLoadedApk.getClass();
            Field mActivityThreadField = mLoadedApkClass.getDeclaredField("mActivityThread");
            mActivityThreadField.setAccessible(true);
            Object mActivityThread = mActivityThreadField.get(mLoadedApk);
            Class mActivityThreadClass = mActivityThread.getClass();
            Field mActivitiesField = mActivityThreadClass.getDeclaredField("mActivities");
            mActivitiesField.setAccessible(true);
            Object mActivities = mActivitiesField.get(mActivityThread);
            // 注意这里一定写成Map,低版本这里用的是HashMap,高版本用的是ArrayMap
            if (mActivities instanceof Map) {
                @SuppressWarnings("unchecked")
                Map arrayMap = (Map) mActivities;
                for (Map.Entry entry : arrayMap.entrySet()) {
                    Object value = entry.getValue();
                    Class activityClientRecordClass = value.getClass();
                    Field activityField = activityClientRecordClass.getDeclaredField("activity");
                    activityField.setAccessible(true);
                    Object o = activityField.get(value);
                    list.add((Activity) o);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            list = null;
        }
        return list;
    }

 

 

你可能感兴趣的:(Android)