美文网首页
初始化其他Module的Application

初始化其他Module的Application

作者: 天青色等Y雨 | 来源:发表于2021-12-10 09:28 被阅读0次

在主工程的Application中进行初始化,OtherApplication不需要在其Module的清单文件中配置。

class AppApplication : Application() {

    private var mOtherApplication: OtherApplication? = null

    override fun onCreate() {
        super.onCreate()

        mOtherApplication?.onCreate()
    }

    @SuppressLint("DiscouragedPrivateApi")
    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)

        mOtherApplication = getOtherApplicationInstance(base)

        try {
            // 通过反射调用OtherApplication的attach方法
            val method = Application::class.java.getDeclaredMethod("attach", Context::class.java)
            method.isAccessible = true
            method.invoke(mOtherApplication, baseContext)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun getOtherApplicationInstance(context: Context?): OtherApplication? {
        try {
            val classLoader = context?.classLoader
            val cls = classLoader?.loadClass(OtherApplication::class.java.name)
            return (cls?.newInstance() as OtherApplication)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }
}

相关文章

网友评论

      本文标题:初始化其他Module的Application

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