android8.0 反射Application 启动过程
16lz
2021-01-23
private void proxy(){ try{ //获取当前ActivityThread Class ClassActivityThread=Class.forName("android.app.ActivityThread"); Method methodCurrentActivityThread=ClassActivityThread.getDeclaredMethod("currentActivityThread"); Object activityThread=methodCurrentActivityThread.invoke(null); //获取当前ActivityThread的mInstrumentation字段 Field fieldmInstrumentation=ClassActivityThread.getDeclaredField("mInstrumentation"); fieldmInstrumentation.setAccessible(true); Object mInstrumentation=fieldmInstrumentation.get(activityThread); //构造LoadAPK 调用LoadedApk(ActivityThread, ApplicationInfo, // CompatibilityInfo,ClassLoader,boolean,boolean,boolean)构造函数 Class ClassInstrumentation=Class.forName("android.app.Instrumentation"); Class ClassContextImpl= Class.forName("android.app.ContextImpl"); //loadAPK packageInfo Class classLoadedApk= Class.forName("android.app.LoadedApk"); Class classCompatibilityInfo=Class.forName("android.content.res.CompatibilityInfo"); Field fieldDEFAULT_COMPATIBILITY_INFO=classCompatibilityInfo.getDeclaredField("DEFAULT_COMPATIBILITY_INFO"); Object DEFAULT_COMPATIBILITY_INFO=fieldDEFAULT_COMPATIBILITY_INFO.get(null); UserHandle.class.getDeclaredMethod("myUserId").invoke(null); Constructor constructor=classLoadedApk.getConstructor(ClassActivityThread, ApplicationInfo.class, classCompatibilityInfo,ClassLoader.class,boolean.class,boolean.class,boolean.class); ApplicationInfo applicationInfo=this.getApplicationInfo(); applicationInfo.className="com.xx.xx.CustomApp"; Object loadAPK=constructor.newInstance(activityThread,applicationInfo, DEFAULT_COMPATIBILITY_INFO,this.getClassLoader(),false,true,false); //执行创建Application Method methodCreateAppContext=ClassContextImpl.getDeclaredMethod("createAppContext",ClassActivityThread,classLoadedApk); methodCreateAppContext.setAccessible(true); Object appContext =methodCreateAppContext.invoke(null,activityThread,loadAPK); CustomApp globalApp= (CustomApp) ClassInstrumentation.getDeclaredMethod("newApplication",ClassLoader.class,String.class, Context.class).invoke(mInstrumentation,this.getClassLoader(),"com.xx.xx.CustomApp",appContext); Field fieldAppication=classLoadedApk.getDeclaredField("mApplication"); fieldAppication.setAccessible(true); fieldAppication.set(loadAPK,globalApp); //调用onCreate() globalApp.onCreate(); globalApp.setAttached(true); }catch (Exception e){ e.printStackTrace(); } //globalApp.onCreate(); }
代码没有经过考验,仅供学习参考
更多相关文章
- android之检查service运行状态函数
- Android Studio 基础 之 一键快速实现一个类的 构造函数、getter
- Android Studio如何提示函数用法
- Android Studio怎样提示函数使用方法
- Android NDK编程实现终端功能(调用system函数)
- 浅谈android系统java调用C++函数传参过程
- Android 查询字段