美文网首页
通过类名反射获取acitivity

通过类名反射获取acitivity

作者: 我的资讯圈 | 来源:发表于2018-07-09 17:21 被阅读8次

    public static ActivitygetActivity() {

    Class activityThreadClass =null;

        try {

    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 (NoSuchMethodException e) {

    e.printStackTrace();

        }catch (IllegalAccessException e) {

    e.printStackTrace();

        }catch (InvocationTargetException e) {

    e.printStackTrace();

        }catch (NoSuchFieldException e) {

    e.printStackTrace();

        }

    return null;

    }

    相关文章

      网友评论

          本文标题:通过类名反射获取acitivity

          本文链接:https://www.haomeiwen.com/subject/nsutpftx.html