How to reference the current or main activity from another class

后端 未结 13 992
难免孤独
难免孤独 2021-01-30 12:39

I often find myself needing to access methods that require referencing some activity. For example, to use getWindowManager, I need to access some Activity. But ofte

13条回答
  •  半阙折子戏
    2021-01-30 13:06

    public static Activity getLaunchActivity()
    {
        final Class activityThreadClass = Class.forName("android.app.ActivityThread");
    
        final Method methodApp = activityThreadClass.getMethod("currentApplication");
        App = (Application) methodApp.invoke(null, (Object[]) null);
        Intent launcherIntent = App.getPackageManager().getLaunchIntentForPackage(App.getPackageName());
        launchActivityInfo = launcherIntent.resolveActivityInfo(App.getPackageManager(), 0);
        Class clazz;
        try
        {
            clazz = Class.forName(launchActivityInfo.name);
            if(clazz != null)
                return Activity.class.cast(clazz.newInstance());
        }
        catch (Exception e)
        {}
    
        return null;
    }
    

提交回复
热议问题