系统相关app应用开发框架探索Android开源框架

探索Android开源框架 - 10. 插件化原理

2021-12-27  本文已影响0人  今阳说

什么是插件化

插件化发展史

  1. AndroidDynamicLoader:给予 Fragment 实现了插件化框架,可以动态加载插件中的 Fragment 实现页面的切换;
  2. dynamic-load-apk(任玉刚):最早使用ProxyActivity这种静态代理技术,由ProxyActivity去控制插件中PluginActivity的生命周期(缺点:插件中的activity必须继承PluginActivity,开发时要小心处理context);
  3. DroidPlugin:通过Hook系统服务的方式启动插件中的Activity,使得开发插件的过程和开发普通的app没有什么区别(缺点:由于hook过多系统服务,异常复杂且不够稳定)
  1. 携程 DynamicApk
  2. VirtualApp:能够完全模拟app的运行环境,能够实现app的免安装运行和双开技术
  3. Small: 一个跨平台插件化框架
  4. 360 RePlugin
  5. 滴滴 VirtualApk
  6. 阿里 Atlas:一个结合组件化和热修复技术的一个app基础框架,号称是一个容器化框架
  7. 腾讯 Shadow:一个完全无Hack,甚至零反射实现的Android插件框架,插件的代码完全是一个正常可安装的App代码,无需引用任何Shadow的库

插件化原理

类加载 ClassLoader

java 中的 ClassLoader:

  1. BootstrapClassLoader:负责加载 JVM 运行时的核心类,比如 JAVA_HOME/lib/rt.jar 等
  2. ExtensionClassLoader:负责加载 JVM 的扩展类,比如 JAVA_HOME/lib/ext 下面的 jar 包
  3. AppClassLoader:负责加载 classpath 里的 jar 包和目录

android 中的 ClassLoader:

双亲委派机制:

如何加载插件中的类

单DexClassLoader
binding.btnSingleDexClassLoader.setOnClickListener {
    loadDex(this, listOf(plugin001Path,plugin002Path))

    val clazzApp = Class.forName("com.jinyang.plugindemo.TestApp")
    val methodApp = clazzApp.getMethod("test")
    methodApp.invoke(clazzApp.newInstance())

    val clazzPlugin001 = Class.forName("com.jinyang.plugin001.TestPlugin001")
    val methodPlugin001 = clazzPlugin001.getMethod("test")
    methodPlugin001.invoke(clazzPlugin001.newInstance())

    val clazzPlugin002 = Class.forName("com.jinyang.plugin002.TestPlugin002")
    val methodPlugin002 = clazzPlugin002.getMethod("test")
    methodPlugin002.invoke(clazzPlugin002.newInstance())
}

fun loadDex(context: Context, pluginPaths: List<String>) {
    try {
        // 获取 pathList
        val systemClassLoader = Class.forName("dalvik.system.BaseDexClassLoader")
        val pathListField = systemClassLoader.getDeclaredField("pathList")
        pathListField.isAccessible = true
        // 获取 dexElements
        val dexPathListClass = Class.forName("dalvik.system.DexPathList")
        val dexElementsField = dexPathListClass.getDeclaredField("dexElements")
        dexElementsField.isAccessible = true
        // 获取宿主的Elements
        val hostClassLoader = context.classLoader
        val hostPathList = pathListField.get(hostClassLoader)
        val hostElements = dexElementsField.get(hostPathList) as kotlin.Array<*>
        var newElements: kotlin.Array<*> = hostElements
        // 遍历获取插件的Elements
        for (path in pluginPaths) {
            val pluginClassLoader = PathClassLoader(path, context.classLoader)
            val pluginPathList = pathListField.get(pluginClassLoader)
            val pluginElements = dexElementsField.get(pluginPathList) as kotlin.Array<*>
            // 创建数组
            val temp = Array.newInstance(
                pluginElements.javaClass.componentType!!,
                newElements.size + pluginElements.size
            ) as kotlin.Array<*>

            // 给新数组赋值,先用宿主的,再用插件的
            System.arraycopy(newElements, 0, temp, 0, newElements.size)
            System.arraycopy(
                pluginElements,
                0,
                temp,
                newElements.size,
                pluginElements.size
            )
            // 合并
            dexElementsField.set(hostPathList, temp)
            newElements = temp
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
}
多DexClassLoader
val nativeLibDir = File(filesDir, "pluginlib").absolutePath
val dexOutPath = File(filesDir, "dexout").absolutePath

val plugin001Path = File(filesDir.absolutePath, "plugin001.apk").absolutePath
val pluginClassLoader = DexClassLoader(plugin001Path, dexOutPath, nativeLibDir, this::class.java.classLoader)

val plugin002Path: String = File(filesDir.absolutePath, "plugin002.apk").absolutePath
val pluginClassLoader2 = DexClassLoader(plugin002Path, dexOutPath, nativeLibDir, this::class.java.classLoader)

资源加载

资源路径的处理
1. 合并式:
binding.btnPrintResources.setOnClickListener {
    val plugin001Path = File(filesDir.absolutePath, "plugin001.apk").absolutePath
    val plugin002Path: String = File(filesDir.absolutePath, "plugin002.apk").absolutePath
    val mResources = loadResources(this,resources.assets, listOf(pluginPath, pluginPath2))
    val strAppId = mResources?.getIdentifier("str_app", "string", "com.jinyang.plugindemo")
    log("str_app:"+ strAppId?.let { it1 -> mResources.getString(it1) })
    val strPlugin001Id = mResources?.getIdentifier("str_plugin001", "string", "com.jinyang.plugindemo")
    log("str_plugin001:"+ strPlugin001Id?.let { it1 -> mResources.getString(it1) })
    val strPlugin002Id = mResources?.getIdentifier("str_plugin002", "string", "com.jinyang.plugindemo")
    log("str_plugin002:"+ strPlugin002Id?.let { it1 -> mResources.getString(it1) })
}

fun loadResources(context: Context,assetManager:AssetManager, pluginPaths: List<String>): Resources? {
        try {
            val addAssetPathMethod = assetManager::class.java.getDeclaredMethod("addAssetPath", String::class.java)
            addAssetPathMethod.isAccessible = true
            for (path in pluginPaths) {
                addAssetPathMethod.invoke(assetManager, path)
            }
            return Resources(
                assetManager,
                context.resources.displayMetrics,
                context.resources.configuration
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
}
2. 独立式:
open class PluginBaseActivity : Activity() {
    private var pluginClassLoader: ClassLoader? = null
    private var pluginPath: String?=null
    private var pluginAssetManager: AssetManager? = null
    private var pluginResources: Resources? = null
    private var pluginTheme: Resources.Theme? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val nativeLibDir = File(filesDir, "pluginlib").absolutePath
        val dexOutPath = File(filesDir, "dexout").absolutePath
        pluginPath = File(filesDir.absolutePath, "plugin002.apk").absolutePath
        pluginClassLoader = DexClassLoader(pluginPath, dexOutPath, nativeLibDir, this::class.java.classLoader)
        handleResources()
    }

    override fun getResources(): Resources? {
        return pluginResources ?: super.getResources()
    }

    override fun getAssets(): AssetManager {
        return pluginAssetManager ?: super.getAssets()
    }

    override fun getClassLoader(): ClassLoader {
        return pluginClassLoader ?: super.getClassLoader()
    }

    private fun handleResources() {
        try {
            pluginAssetManager = AssetManager::class.java.newInstance()
            val addAssetPathMethod = pluginAssetManager?.javaClass?.getMethod("addAssetPath", String::class.java)
            addAssetPathMethod?.invoke(pluginAssetManager, pluginPath)
        } catch (e: Exception) {
        }
        pluginResources = Resources(pluginAssetManager, super.getResources().displayMetrics, super.getResources().configuration)
        pluginTheme = pluginResources?.newTheme()
        pluginTheme?.setTo(super.getTheme())
    }
}
解决资源id冲突问题的方法:
  1. 修改aapt源码,定制aapt工具,编译期间修改PP段;(DynamicAPK使用此方案),原理参考:Android中如何修改编译的资源ID值
  2. 修改aapt的产物resources.arsc文件,即,编译后期重新整理插件Apk的资源,编排ID;(VirtualApk使用此方案),原理参考:插件化-解决插件资源ID与宿主资源ID冲突的问题
  3. 通过配置aaptOptions,build.gradle中的android节点加入如下代码,不过此方法只有在compileSdkVersion为28及以上才生效
android {
    aaptOptions {
        additionalParameters  "--package-id", "0x66","--allow-reserved-package-id"
    }
    ...
}
Context的处理
// 获取自己创建的resources
val resources = LoadUtils.getResources(application)
// 创建自己的Context
mContext = ContextThemeWrapper(baseContext, 0)
// 把自己的Context中的resources替换为我们自己的
val clazz = mContext::class.java
val mResourcesField = clazz.getDeclaredField("mResources")
mResourcesField.isAccessible = true
mResourcesField.set(mContext, resources)
public static void hookResources(Context base, Resources resources) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return;
    }
    try {
        // 替换主工程context中LoadedApk的mResource对象
        Reflector reflector = Reflector.with(base);
        reflector.field("mResources").set(resources);
        Object loadedApk = reflector.field("mPackageInfo").get();
        Reflector.with(loadedApk).field("mResources").set(resources);

        // 将新的Resource添加到主工程ActivityThread的mResourceManager中,并且根据Android版本做了不同处理
        Object activityThread = ActivityThread.currentActivityThread();
        Object resManager;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            resManager = android.app.ResourcesManager.getInstance();
        } else {
            resManager = Reflector.with(activityThread).field("mResourcesManager").get();
        }
        Map<Object, WeakReference<Resources>> map = Reflector.with(resManager).field("mActiveResources").get();
        Object key = map.keySet().iterator().next();
        map.put(key, new WeakReference<>(resources));
    } catch (Exception e) {
        Log.w(TAG, e);
    }
}

加载四大组件

加载 插件Activity

插件Activity的两个问题
解决方法
  1. 手动去调用插件 Activity 的生命周期;
  2. 欺骗系统,让系统以为 Activity 是注册在 Manifest 中的
1. 反射实现 调用 插件Activity 的生命周期:
  1. 创建一个反射生命周期的工具类ReflectActivityLifeCircle,其中通过class.getMethod来反射调用Activity的各个声明周期方法,代码如下:
class ReflectActivityLifeCircle(activity: String?, activityClassLoader: ClassLoader?) {
    private var clazz: Class<Activity>? = activityClassLoader?.loadClass(activity) as Class<Activity>?
    private var activity: Activity? = clazz?.newInstance()

    private fun getMethod(methodName: String, vararg params: Class<*>): Method? {
        return clazz?.getMethod(methodName, *params)
    }

    fun attach(proxyActivity: Activity?) {
        getMethod("attach", Activity::class.java)?.invoke(activity, proxyActivity)   }

    fun onCreate(savedInstanceState: Bundle?) {
        getMethod("onCreate", Bundle::class.java)?.invoke(activity, savedInstanceState)
    }

    fun onStart() {
        getMethod("onStart")?.invoke(activity)
    }

    fun onResume() {
        getMethod("onResume")?.invoke(activity)
    }

    fun onPause() {
        getMethod("onPause")?.invoke(activity)
    }

    fun onStop() {
        getMethod("onStop")?.invoke(activity)
    }

    fun onDestroy() {
        getMethod("onDestroy")?.invoke(activity)
    }
}
  1. 在宿主中创建一个代理Activity,其生命周期直接调用ReflectActivityLifeCircle的方法,通过反射调用插件Activity的生命周期,代码如下
class ProxyReflectActivity : ProxyBaseActivity() {
    private var reflectActivityLifeCircle: ReflectActivityLifeCircle? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val nativeLibDir = File(filesDir, "pluginlib").absolutePath
        val dexOutPath = File(filesDir, "dexout").absolutePath
        val pluginPath = intent.getStringExtra("pluginPath")
        val pluginActivityName = intent.getStringExtra("activityName")
        val pluginClassLoader = DexClassLoader(pluginPath, dexOutPath, nativeLibDir, this::class.java.classLoader)
        reflectActivityLifeCircle= ReflectActivityLifeCircle(pluginActivityName,pluginClassLoader)
        reflectActivityLifeCircle?.attach(this)
        reflectActivityLifeCircle?.onCreate(savedInstanceState)
    }

    override fun onStart() {
        super.onStart()
        reflectActivityLifeCircle?.onStart()
    }

    override fun onResume() {
        super.onResume()
        reflectActivityLifeCircle?.onResume()
    }

    override fun onPause() {
        super.onPause()
        reflectActivityLifeCircle?.onPause()
    }

    override fun onStop() {
        super.onStop()
        reflectActivityLifeCircle?.onStop()
    }

    override fun onDestroy() {
        super.onDestroy()
        reflectActivityLifeCircle?.onDestroy()
    }

    companion object{
        fun startPluginActivity(context: Context, pluginPath: String, activityName: String) {
            val intent = Intent(context, ProxyReflectActivity::class.java)
            intent.putExtra("pluginPath", pluginPath)
            intent.putExtra("activityName", activityName)
            context.startActivity(intent)
        }
    }

}
2. 通过接口实现 调用 插件Activity 的生命周期
  1. 定义一个接口,注意宿主和插件中用的接口全路径应相同
interface IPluginActivity {
    fun attach(proxyActivity: Activity)
    fun onCreate(savedInstanceState: Bundle?)
    fun onStart()
    fun onResume()
    fun onPause()
    fun onStop()
    fun onDestroy()
}
  1. 在插件的baseActivity中实现该接口
open class BasePluginActivity : Activity(), IPluginActivity {
    var proxyActivity: Activity? = null

    override fun attach(proxyActivity: Activity) {
        this.proxyActivity = proxyActivity
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        if (proxyActivity == null) {
            super.onCreate(savedInstanceState)
        }
    }

    override fun setContentView(layoutResID: Int) {
        log("proxyActivity=$proxyActivity,layoutResID=$layoutResID")
        proxyActivity?.let {
            it.setContentView(layoutResID)
        } ?: run {
            super.setContentView(layoutResID)
        }
    }

    override fun setContentView(view: View?) {
        proxyActivity?.let {
            it.setContentView(view)
        } ?: run {
            super.setContentView(view)
        }
    }

    override fun onStart() {
        if (proxyActivity == null) {
            super.onStart()
        }
    }

    override fun onResume() {
        if (proxyActivity == null) {
            super.onResume()
        }
    }

    override fun onPause() {
        if (proxyActivity == null) {
            super.onPause()
        }
    }

    override fun onStop() {
        if (proxyActivity == null) {
            super.onStop()
        }
    }

    override fun onDestroy() {
        if (proxyActivity == null) {
            super.onDestroy()
        }
    }

    override fun getResources(): Resources? {
        if (proxyActivity == null) {
            return super.getResources()
        }
        return proxyActivity?.resources
    }

    override fun getTheme(): Resources.Theme? {
        if (proxyActivity == null) {
            return super.getTheme()
        }
        return proxyActivity?.theme
    }

    override fun getLayoutInflater(): LayoutInflater {
        if (proxyActivity == null) {
            return super.getLayoutInflater()
        }
        return proxyActivity?.layoutInflater!!
    }
}
  1. 在宿主中创建一个代理Activity,通过插件的classLoader及插件ActivityName获取插件Activity实例,并强转为IPluginActivity类型,并在宿主Activity的生命周期中调用IPluginActivity对应方法
class ProxyInterfaceActivity : Activity() {
    private  var activity: IPluginActivity?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val nativeLibDir = File(filesDir, "pluginlib").absolutePath
        val dexOutPath = File(filesDir, "dexout").absolutePath
        val pluginPath = intent.getStringExtra("pluginPath")
        val pluginActivityName = intent.getStringExtra("activityName")
        val pluginClassLoader = DexClassLoader(pluginPath, dexOutPath, nativeLibDir, this::class.java.classLoader)
        //通过插件的classLoader及插件ActivityName获取插件Activity实例,并强转为IPluginActivity类型
        activity=pluginClassLoader?.loadClass(pluginActivityName)?.newInstance() as IPluginActivity
        //在宿主Activity的生命周期中调用IPluginActivity对应生命周期方法
        activity?.attach(this)
        activity?.onCreate(savedInstanceState)
    }

    override fun onStart() {
        super.onStart()
        activity?.onStart()
    }

    override fun onResume() {
        super.onResume()
        activity?.onResume()
    }

    override fun onPause() {
        super.onPause()
        activity?.onPause()
    }

    override fun onStop() {
        super.onStop()
        activity?.onStop()
    }

    override fun onDestroy() {
        super.onDestroy()
        activity?.onDestroy()
    }

    companion object {
        fun startPluginActivity(context: Context, pluginPath: String, activityName: String) {
            val intent = Intent(context, ProxyInterfaceActivity::class.java)
            intent.putExtra("pluginPath", pluginPath)
            intent.putExtra("activityName", activityName)
            context.startActivity(intent)
        }
    }
}
3. Hook实现
Activity的启动过程
Hook IActivityManager方案实现
  1. 在宿主中创建一个占坑Activity
class StubHookActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }
}

<activity
    android:name=".hook.StubHookActivity"
    android:exported="false" />
  1. 使用占坑Activity通过AMS验证
// Android 8.0与7.0的AMS家族有一些差别,主要是Android 8.0去掉了AMS的代理ActivityManagerProxy,代替它的是IActivityManager,直接采用AIDL来进行进程间通信。
// Android7.0的Activity的启动会调用ActivityManagerNative的getDefault方法, Android8.0的Activity的启动会调用ActivityManager的getService方法,两者都返回了IActivityManager类型的对象。
public static void hookAMS() {
    try {
        Object singleTon = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            //android 29或以上版本的API
            @SuppressLint("PrivateApi")
            Class<?> activityManagerClass = Class.forName("android.app.ActivityTaskManager");
            Field iActivityManagerSingletonField = activityManagerClass.getDeclaredField("IActivityTaskManagerSingleton");
            iActivityManagerSingletonField.setAccessible(true);
            singleTon = iActivityManagerSingletonField.get(null);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //android 26或以上版本的API是一样的
            Class<?> activityManagerClass = Class.forName("android.app.ActivityManager");
            Field iActivityManagerSingletonField = activityManagerClass.getDeclaredField("IActivityManagerSingleton");
            iActivityManagerSingletonField.setAccessible(true);
            singleTon = iActivityManagerSingletonField.get(null);
        } else {
            //android 26或以下版本的API是一个系列
            Class<?> activityManagerClass = Class.forName("android.app.ActivityManagerNative");
            Field iActivityManagerSingletonField = activityManagerClass.getDeclaredField("gDefault");
            iActivityManagerSingletonField.setAccessible(true);
            singleTon = iActivityManagerSingletonField.get(null);
        }
        Class<?> singleTonClass = Class.forName("android.util.Singleton");
        Field mInstanceField = singleTonClass.getDeclaredField("mInstance");
        mInstanceField.setAccessible(true);
        // 获取到IActivityManagerSingleton的对象
        final Object iActivityManager = mInstanceField.get(singleTon);
        Class<?> iActivityManagerClass;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            iActivityManagerClass = Class.forName("android.app.IActivityTaskManager");
        } else {
            iActivityManagerClass = Class.forName("android.app.IActivityManager");
        }

        Object newInstance = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{iActivityManagerClass},
                (o, method, args) -> {
                    if ("startActivity".equals(method.getName())) {
                        // 拦截startActivity方法,接着获取参数args中第一个Intent对象
                        // 它是原本要启动插件Plugin002Activity的Intent
                        Intent intent = null;
                        int index = 0;
                        for (int i = 0; i < args.length; i++)
                            if (args[i] instanceof Intent) {
                                index = i;
                                break;
                            }
                        intent = (Intent) args[index];
                        //新建一个subIntent用来启动的StubActivity
                        Intent subIntent = new Intent();
                        String packageName = "com.jinyang.plugindemo";
                        subIntent.setClassName(packageName, packageName + ".hook.StubHookActivity");
                        //将这个Plugin002Activity的Intent保存到subIntent中,便于以后还原Plugin002Activity
                        subIntent.putExtra(HookHelper.TARGET_INTENT, intent);
                        //用subIntent赋值给参数args,这样启动的目标就变为了StubActivity,用来通过AMS的校验。
                        args[index] = subIntent;
                    }
                    return method.invoke(iActivityManager, args);
                });
        mInstanceField.set(singleTon, newInstance);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
binding.btnHookIActivityManager.setOnClickListener {
    hookAMS()//可以放到Application中对全局生效
    val intent = Intent()
    val packageName = "com.jinyang.plugindemo"
    val activityName = "com.jinyang.plugin002.Plugin002Activity"
    intent.component = ComponentName(packageName, activityName)
    startActivity(intent)
}
  1. 还原插件Activity:ActivityThread类中有一个静态变量sCurrentActivityThread,用于表示当前的ActivityThread对象,通过替换其mH:Handler, 重写handleMessage并拦截对应的msg,将启动StubHookActivity的Intent替换回启动Plugin002Activity
public static void hookHandler() {
    try {
        // 获取ActivityThread实例
        final Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
        Field activityThreadField = activityThreadClass.getDeclaredField("sCurrentActivityThread");
        activityThreadField.setAccessible(true);
        final Object activityThread = activityThreadField.get(null);
        // 获取Handler实例
        Field mHField = activityThreadClass.getDeclaredField("mH");
        mHField.setAccessible(true);
        Object mH = mHField.get(activityThread);
        Class<?> handlerClass = Class.forName("android.os.Handler");
        Field mCallbackField = handlerClass.getDeclaredField("mCallback");
        mCallbackField.setAccessible(true);
        mCallbackField.set(mH, (Handler.Callback) msg -> {
            switch (msg.what) {
                case 100: // API 28 以前直接接收
                    try {
                        // 获取ActivityClientRecord中的intent对象
                        Field intentField = msg.obj.getClass().getDeclaredField("intent");
                        intentField.setAccessible(true);
                        Intent proxyIntent = (Intent) intentField.get(msg.obj);
                        // 拿到插件的Intent
                        Intent intent = proxyIntent.getParcelableExtra(TARGET_INTENT);
                        // 替换回来
                        proxyIntent.setComponent(intent.getComponent());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 159: // API 28 以后加入了 lifecycle, 这里msg发生了变化
                    try {
                        Field mActivityCallbacksField = msg.obj.getClass().getDeclaredField("mActivityCallbacks");
                        mActivityCallbacksField.setAccessible(true);
                        List<Object> mActivityCallbacks = (List<Object>) mActivityCallbacksField.get(msg.obj);
                        for (int i = 0; i < mActivityCallbacks.size(); i++) {
                            Class<?> itemClass = mActivityCallbacks.get(i).getClass();
                            Log.d("LJY_LOG","itemClass:"+itemClass);
                            if (itemClass.getName().equals("android.app.servertransaction.LaunchActivityItem")) {
                                Field intentField = itemClass.getDeclaredField("mIntent");
                                intentField.setAccessible(true);
                                Intent proxyIntent = (Intent) intentField.get(mActivityCallbacks.get(i));
                                Intent intent = proxyIntent.getParcelableExtra(TARGET_INTENT);
                                proxyIntent.setComponent(intent.getComponent());
                                break;
                            }
                        }
                    } catch (Exception e) {
                        Log.d("LJY_LOG", "e = " + e.getMessage());
                    }
                    break;
                default:
                    break;
            }
            return false;// 这里必须返回false
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}
binding.btnHookIActivityManager.setOnClickListener {
    hookAMS()
    hookHandler()
    val intent = Intent()
    val packageName = "com.jinyang.plugindemo"
    val activityName = "com.jinyang.plugin002.Plugin002Activity"
    intent.component = ComponentName(packageName, activityName)
    startActivity(intent)
}
binding.btnHookIActivityManager.setOnClickListener {
    loadDex(this, listOf(plugin001Path,plugin002Path))
    hookAMS()
    hookHandler()
    val intent = Intent()
    val packageName = "com.jinyang.plugindemo"
    val activityName = "com.jinyang.plugin002.Plugin002Activity"
    intent.component = ComponentName(packageName, activityName)
    startActivity(intent)
}
class Plugin002Activity : PluginBaseActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_plugin002)
    }
}

open class PluginBaseActivity2 : Activity() {
    private var mResources: Resources? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val plugin002Path: String = File(filesDir.absolutePath, "plugin002.apk").absolutePath
        mResources = loadResources(this, AssetManager::class.java.newInstance(), listOf( plugin002Path))
    }

    override fun getResources(): Resources? {
        return mResources ?: super.getResources()
    }

    override fun getAssets(): AssetManager {
        return mResources?.assets ?: super.getAssets()
    }
}
Hook Instrumentation方案实现
  1. 自定义Instrumentation
class InstrumentationProxy(
    var realContext: Context,
    var base: Instrumentation,
    var context: ContextWrapper
) : Instrumentation() {
    private val KEY_COMPONENT = "commontec_component"

    companion object {
        /**
         * hook 系统,替换 Instrumentation 为我们自己的 InstrumentationProxy
         */
        fun inject(activity: Activity, context: ContextWrapper) {
            // Reflect 是从 VirtualApp 里拷贝的反射工具类,使用很流畅~
            val reflect = Reflect.on(activity)
            val activityThread = reflect.get<Any>("mMainThread")
            val base = Reflect.on(activityThread).get<Instrumentation>("mInstrumentation")
            val mInstrumentation = InstrumentationProxy(activity, base, context)
            Reflect.on(activityThread).set("mInstrumentation", mInstrumentation)
            Reflect.on(activity).set("mInstrumentation", mInstrumentation)
        }
    }

    /**
     * newActivity 是创建 Activity 实例,这里要返回真正需要运行的插件 Activity,
     * 这样后面系统就会基于这个 Activity 实例来进行对应的生命周期的调用。
     */
    override fun newActivity(cl: ClassLoader, className: String, intent: Intent): Activity? {
        val componentName = intent.getParcelableExtra<ComponentName>(KEY_COMPONENT)
        var clazz = context.classLoader.loadClass(componentName?.className)
        intent.component = componentName
        return clazz.newInstance() as Activity?
    }

    /**
     *  hook 系统的资源处理方式: 生成 Resources 以后,直接反射替换掉 Activity 中的 mResource 变量即可
     */
    private fun injectActivity(activity: Activity?) {
        val intent = activity?.intent
        val base = activity?.baseContext
        try {
            //反射替换 mResources 资源
            Reflect.on(base).set("mResources", context.resources)
            Reflect.on(activity).set("mResources", context.resources)
            Reflect.on(activity).set("mBase", context)
            Reflect.on(activity).set("mApplication", context.applicationContext)
            // for native activity
            val componentName: ComponentName? =
                intent!!.getParcelableExtra<ComponentName>(KEY_COMPONENT)
            val wrapperIntent = Intent(intent)
            wrapperIntent.setClassName(componentName?.packageName!!, componentName.className)
            activity.intent = wrapperIntent

        } catch (e: Exception) {
        }
    }

    override fun callActivityOnCreate(activity: Activity?, icicle: Bundle?) {
        injectActivity(activity)
        super.callActivityOnCreate(activity, icicle)
    }

    override fun callActivityOnCreate(
        activity: Activity?,
        icicle: Bundle?,
        persistentState: PersistableBundle?
    ) {
        injectActivity(activity)
        super.callActivityOnCreate(activity, icicle, persistentState)
    }

    /**
     *  替换 intent 中的类名为占位 Activity 的类名,这样系统在 Manifest 中查找的时候就可以找到 Activity
     */
    private fun injectIntent(intent: Intent?) {
        var component: ComponentName? = null
        var oldComponent = intent?.component
        if (component == null || component.packageName == realContext.packageName) {
            component = ComponentName(
                "com.jinyang.plugindemo",
                "com.jinyang.plugindemo.hook.StubHookActivity"
            )
            intent?.component = component
            intent?.putExtra(KEY_COMPONENT, oldComponent)
        }
    }

    /**
     * execStartActivity 是在启动 Activity 的时候必经的一个过程,这时还没有到达 AMS,
     * 所以,在这里把 Activity 替换成宿主中已经注册的 StubActivity,
     * 这样 AMS 在检测 Activity 的时候就认为已经注册过了
     */
    fun execStartActivity(
        who: Context,
        contextThread: IBinder,
        token: IBinder,
        target: Activity,
        intent: Intent,
        requestCode: Int
    ): Instrumentation.ActivityResult? {
        log("exec...")
        injectIntent(intent)
        return Reflect.on(base)
            .call("execStartActivity", who, contextThread, token, target, intent, requestCode).get()
    }

    fun execStartActivity(
        who: Context?,
        contextThread: IBinder?,
        token: IBinder?,
        target: Activity?,
        intent: Intent,
        requestCode: Int,
        options: Bundle?
    ): Instrumentation.ActivityResult? {
        log("exec...")
        injectIntent(intent)
        return Reflect.on(base)
            .call(
                "execStartActivity",
                who,
                contextThread,
                token,
                target,
                intent,
                requestCode,
                options ?: Bundle()
            )
            .get()
    }

    fun execStartActivity(
        who: Context,
        contextThread: IBinder,
        token: IBinder,
        target: Fragment,
        intent: Intent,
        requestCode: Int,
        options: Bundle?
    ): Instrumentation.ActivityResult? {
        log("exec...")
        injectIntent(intent)
        return Reflect.on(base)
            .call(
                "execStartActivity",
                who,
                contextThread,
                token,
                target,
                intent,
                requestCode,
                options ?: Bundle()
            )
            .get()
    }

    fun execStartActivity(
        who: Context,
        contextThread: IBinder,
        token: IBinder,
        target: String,
        intent: Intent,
        requestCode: Int,
        options: Bundle?
    ): Instrumentation.ActivityResult? {
        log("exec...")
        injectIntent(intent)
        return Reflect.on(base)
            .call(
                "execStartActivity",
                who,
                contextThread,
                token,
                target,
                intent,
                requestCode,
                options ?: Bundle()
            )
            .get()
    }
}

  1. 调用InstrumentationProxy.inject,hook系统,替换 Instrumentation 为我们自己的 AppInstrumentation,再进行跳转
binding.btnHookInstrumentation.setOnClickListener {
    InstrumentationProxy.inject(
        this,
        loadContext(this, resources.assets, listOf(plugin001Path, plugin002Path))
    )
    val intent = Intent()
    intent.setClass(this, pluginClassLoader.loadClass(activityName))
    startActivity(intent)
}

fun loadContext(baseContext: Context,
                assetManager: AssetManager,
                pluginPaths: List<String>): ContextWrapper {
    loadDex(baseContext, pluginPaths)
    val resources = loadResources(baseContext,assetManager, pluginPaths)
    // 创建自己的Context
    val mContext = ContextThemeWrapper(baseContext, 0)
    // 把自己的Context中的resources替换为我们自己的
    val clazz = mContext::class.java
    val mResourcesField = clazz.getDeclaredField("mResources")
    mResourcesField.isAccessible = true
    mResourcesField.set(mContext, resources)
    return mContext
}

加载 插件Service

  1. 插件中创建一个service
class PluginService : Service() {

    override fun onCreate() {
        log("plugin onCreate")
        super.onCreate()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        log("plugin onStartCommand")
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        log("plugin onDestroy")
        super.onDestroy()
    }

    override fun onBind(intent: Intent?): IBinder? {
        log("plugin onBind")
        return null
    }

    override fun onUnbind(intent: Intent?): Boolean {
        log("plugin onUnbind")
        return super.onUnbind(intent)
    }

}
  1. 在宿主 app 里添加一个占位 Service,然后在对应的生命周期里调用插件 Service 的生命周期方法
<service android:name=".service.StubService" />

class StubService : Service() {
    var serviceName: String? = null
    var pluginService: Service? = null

    companion object {
        var pluginClassLoader: ClassLoader? = null
        fun startService(context: Context, classLoader: ClassLoader, serviceName: String) {
            log("StubService.startService")
            pluginClassLoader = classLoader
            val intent = Intent(context, StubService::class.java)
            intent.putExtra("serviceName", serviceName)
            context.startService(intent)
        }

        fun stopService(context: Context, classLoader: ClassLoader, serviceName: String) {
            log("StubService.stopService")
            pluginClassLoader = classLoader
            val intent = Intent(context, StubService::class.java)
            intent.putExtra("serviceName", serviceName)
            context.stopService(intent)
        }
    }

    override fun onCreate() {
        super.onCreate()
        log("StubService.onCreate")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        log("StubService.onStartCommand")
        val res = super.onStartCommand(intent, flags, startId)
        serviceName = intent?.getStringExtra("serviceName")
        if (pluginService == null) {
            pluginService = pluginClassLoader?.loadClass(serviceName)?.newInstance() as Service
            pluginService?.onCreate()
        }
        return pluginService?.onStartCommand(intent, flags, startId) ?: res
    }

    override fun onDestroy() {
        super.onDestroy()
        log("StubService.onDestroy")
        if (pluginService!=null) {
            pluginService?.onDestroy()
            pluginService = null
        }
    }

    override fun onBind(intent: Intent?): IBinder? {
        log("StubService.onBind")
        return pluginService?.onBind(intent)
    }

    override fun onUnbind(intent: Intent?): Boolean {
        log("StubService.onUnbind")
        return pluginService?.onUnbind(intent) ?: super.onUnbind(intent)
    }
}

  1. 通过占坑service启动和结束插件service
val plugin001Path = File(filesDir.absolutePath, "plugin001.apk").absolutePath
val nativeLibDir = File(filesDir, "pluginlib").absolutePath
val dexOutPath = File(filesDir, "dexout").absolutePath
val pluginClassLoader =
    DexClassLoader(plugin001Path, dexOutPath, nativeLibDir, this::class.java.classLoader)
val serviceName = "com.jinyang.plugin001.PluginService"

binding.btnStartService.setOnClickListener {
    StubService.startService(this, pluginClassLoader, serviceName)
}

binding.btnStopService.setOnClickListener {
    StubService.stopService(this, pluginClassLoader, serviceName)
}

加载 插件BroadcastReceiver

  1. 创建一个注册插件广播的工具类
class BroadcastUtils {
    companion object {
        private val broadcastMap = HashMap<String, BroadcastReceiver>()

        fun registerBroadcastReceiver(context: Context, classLoader: ClassLoader, action: String, broadcastName: String) {
            log("BroadcastUtils.registerBroadcastReceiver")
            val receiver = classLoader.loadClass(broadcastName).newInstance() as BroadcastReceiver
            val intentFilter = IntentFilter(action)
            context.registerReceiver(receiver, intentFilter)
            broadcastMap[action] = receiver
        }

        fun unregisterBroadcastReceiver(context: Context, action: String) {
            log("BroadcastUtils.unregisterBroadcastReceiver")
            val receiver = broadcastMap.remove(action)
            if (receiver!=null) {
                context.unregisterReceiver(receiver)
            }
        }
    }
}
  1. 注册并使用插件中的广播
val testAction = "com.ljy.action.testBroadcastReceiver"
val broadcastName = "com.jinyang.plugin001.PluginBroadcastReceiver"
binding.btnRegisterBroadcastReceiver.setOnClickListener {
    BroadcastUtils.registerBroadcastReceiver(
        this,
        pluginClassLoader,
        testAction,
        broadcastName
    )
}
binding.btnSendBroadcast.setOnClickListener {
    sendBroadcast(Intent(testAction))
}
binding.btnUnregisterBroadcastReceiver.setOnClickListener {
    BroadcastUtils.unregisterBroadcastReceiver(this, testAction)
}
/**
 * 将插件apk的AndroidManifest.xml中静态注册的Receiver通过动态registerReceiver注册到宿主Context中
 */
fun parserPluginStaticBroadcast(context: Context, pluginPath: String?) {
    try {
        //实例化 PackageParser对象
        val mPackageParserClass = Class.forName("android.content.pm.PackageParser")
        val mPackageParser = mPackageParserClass.newInstance()
        // 1.执行此方法 public Package parsePackage(File packageFile, int flags),就是为了,拿到Package
        val mPackageParserMethod = mPackageParserClass.getMethod(
            "parsePackage",
            File::class.java,
            Int::class.javaPrimitiveType
        )
        val mPackage = mPackageParserMethod.invoke(
            mPackageParser,
            File(pluginPath),
            PackageManager.GET_ACTIVITIES
        )
        //获取mPackage中的ArrayList<Activity> receivers属性
        val receiversField = mPackage.javaClass.getDeclaredField("receivers")
        val receivers = receiversField[mPackage]
        val arrayList = receivers as ArrayList<*>
        //此Activity不是组件的Activity,是PackageParser里面的内部类
        for (mActivity in arrayList) { // mActivity --> <receiver android:name=".StaticReceiver">
            //通过反射拿到intents ArrayList<II> intents; 一个<receiver>标签可以对应多个Intent-Filter
            val mComponentClass =
                Class.forName("android.content.pm.PackageParser\$Component")
            val intentsField = mComponentClass.getDeclaredField("intents")
            val intents: ArrayList<IntentFilter> = intentsField[mActivity] as ArrayList<*>
            //上面是拿到了IntentFilter,下面就是获取组件的名字 activityInfo.name
            /**
             * 执行此方法,就能拿到 ActivityInfo
             * public static final ActivityInfo generateActivityInfo(Activity a, int flags,
             * PackageUserState state, int userId)
             */
            val mPackageUserState = Class.forName("android.content.pm.PackageUserState")
            val mUserHandle = Class.forName("android.os.UserHandle")
            val userId = mUserHandle.getMethod("getCallingUserId").invoke(null) as Int
            val generateActivityInfoMethod = mPackageParserClass.getDeclaredMethod(
                "generateActivityInfo",
                mActivity.javaClass,
                Int::class.javaPrimitiveType,
                mPackageUserState,
                Int::class.javaPrimitiveType
            )
            generateActivityInfoMethod.isAccessible = true
            val mActivityInfo = generateActivityInfoMethod.invoke(
                null,
                mActivity,
                0,
                mPackageUserState.newInstance(),
                userId
            ) as ActivityInfo
            val receiverClassName = mActivityInfo.name
            Log.e("LJY_LOG", "receiverClassName : $receiverClassName")
            val mStaticReceiverClass = context.classLoader.loadClass(receiverClassName)
            val broadcastReceiver = mStaticReceiverClass.newInstance() as BroadcastReceiver
            for (intentFilter in intents) {
                Log.e("LJY_LOG", "intentFilter mActions size " + intentFilter.countActions())
                context.registerReceiver(broadcastReceiver, intentFilter)
            }
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

加载 插件ContentProvider

  1. 宿主中创建一个占坑的ContentProvider,并在其中通过插件classLoader加载插件ContentProvider
<provider
    android:name=".contentprovider.StubContentProvider"
    android:authorities="com.ljy.StubContentProvider" />

class StubContentProvider : ContentProvider() {

    private var pluginProvider: ContentProvider? = null
    private var uriMatcher: UriMatcher? = UriMatcher(UriMatcher.NO_MATCH)


    override fun insert(uri: Uri, values: ContentValues?): Uri? {
        log("StubContentProvider.insert")
        return loadPluginProvider()?.insert(uri, values)
    }


    override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? {
        log("StubContentProvider.query: uri=$uri")
        if (isPlugin1(uri)) {
            return loadPluginProvider()?.query(uri, projection, selection, selectionArgs, sortOrder)
        }
        return null
    }

    override fun onCreate(): Boolean {
        log("StubContentProvider.onCreate")
        uriMatcher?.addURI("com.ljy.StubContentProvider", "plugin001", 1)
        uriMatcher?.addURI("com.ljy.StubContentProvider", "plugin002", 2)
        return true
    }

    override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int {
        log("StubContentProvider.update")
        return loadPluginProvider()?.update(uri, values, selection, selectionArgs) ?: 0
    }

    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
        log("StubContentProvider.delete")
        return loadPluginProvider()?.delete(uri, selection, selectionArgs) ?: 0
    }

    override fun getType(uri: Uri): String {
        log("StubContentProvider.getType")
        return loadPluginProvider()?.getType(uri) ?: ""
    }

    private fun loadPluginProvider(): ContentProvider? {
        if (pluginProvider == null) {
            pluginProvider = classLoader?.loadClass("com.jinyang.plugin001.PluginContentProvider")?.newInstance() as ContentProvider?
        }
        return pluginProvider
    }

    private fun isPlugin1(uri: Uri?): Boolean {
        log("StubContentProvider.isPlugin1:${uriMatcher?.match(uri)}")
        if (uriMatcher?.match(uri) == 1) {
            return true
        }
        return false
    }
}
  1. 使用
binding.btnQueryContentProvider1.setOnClickListener {
    val uri = Uri.parse("content://com.ljy.StubContentProvider/plugin001")
    val cursor = contentResolver.query(uri, null, null, null, null)
    cursor?.moveToFirst()
    val res = cursor?.getString(0)
    log("provider query res: $res")
    cursor?.close()
}
binding.btnQueryContentProvider2.setOnClickListener {
    val uri = Uri.parse("content://com.ljy.StubContentProvider/plugin002")
    val cursor = contentResolver.query(uri, null, null, null, null)
    cursor?.moveToFirst()
    val res = cursor?.getString(0)
    log("provider query res: $res")
    cursor?.close()
}

Shadow

Shadow原理:

Shadow为什么要求插件和宿主包名一致

Shadow使用

参考

上一篇下一篇

猜你喜欢

热点阅读