美文网首页
通过反射直接获取Application对象

通过反射直接获取Application对象

作者: 刀鱼z | 来源:发表于2020-12-09 09:25 被阅读0次
      public class AppGlobal {
      private static Application sApp;
    
              public static Application getApplication() {
              if (sApp == null) {
            try {
                sApp = (Application) Class.forName("android.app.ActivityThread")
                        .getMethod("currentApplication")
                        .invoke(null, (Object[]) null);
            } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return sApp;
    }
    

    }

    有些场景下,我们需要获取Application,查看android.app.ActivityThread的源码,

      public static Application currentApplication() {
          ActivityThread am = currentActivityThread();
         return am != null ? am.mInitialApplication : null;
      }
    

    我们可以通过反射获取Application

    相关文章

      网友评论

          本文标题:通过反射直接获取Application对象

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