如何获得当前界面Activity对象?

我有一个需求:需要知道android手机上当前显示的界面是哪个Activity(该Activity不一定是自己的App,可能是其他第三方的App,也可能是系统的App,比如桌面,记事本等等)
我现在通过ActivityManager得到了当前界面的ComponentName对象。
_ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
但是那也仅仅是ComponentName对象,或者通过cn.getClassName()获得类的名字String。如何得到它的Activity实例对象呢?

1个回答

老外的这个方法只能获得自己App的Activity对象,不是我想要的。

 public static Activity getActivity() throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException {
        Class activityThreadClass = Class.forName("android.app.ActivityThread");
        Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
        Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
        activitiesField.setAccessible(true);
        HashMap activities = (HashMap) 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;
            }
        }
        return null;
    }
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问