美文网首页
反射获取当前可见activityName

反射获取当前可见activityName

作者: guardm | 来源:发表于2020-07-27 15:27 被阅读0次

    public static String getTopActivityName() {

            long start = System.currentTimeMillis();

            try {

                Class activityThreadClass = Class.forName("android.app.ActivityThread");

                Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);

                Field activitiesField = activityThreadClass.getDeclaredField("mActivities");

                activitiesField.setAccessible(true);

                Map<Object, Object> activities;

                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {

                    activities = (HashMap<Object, Object>) activitiesField.get(activityThread);

                } else {

                    activities = (ArrayMap<Object, Object>) activitiesField.get(activityThread);

                }

                if (activities.size() < 1) {

                    return null;

                }

                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.getClass().getName();

                    }

                }

            } catch (Exception e) {

                e.printStackTrace();

            } finally {

                long cost = System.currentTimeMillis() - start;

                MatrixLog.d(TAG, "[getTopActivityName] Cost:%s", cost);

            }

            return null;

        }

    相关文章

      网友评论

          本文标题:反射获取当前可见activityName

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