其他分享
首页 > 其他分享> > 做安卓SDK如何获取当前Activity。

做安卓SDK如何获取当前Activity。

作者:互联网

安卓开发中获取当前Activity我们平时一般采用如下两种方式

但做SDK的时候Application不是我们写的,其它的activity也可能是接入方开启的,这时我们就无法通过以上方式获取。此时可以采用反射系统的Activity管理类(ActivityThread)的方式获取。代码如下。

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

标签:做安卓,Activity,printStackTrace,activityRecord,activity,catch,pausedField,SDK
来源: https://blog.csdn.net/HongEnIT/article/details/118577798