在主工程的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
}
}