我试图使用ServiceLoader在动态特性模块中启动一个片段,如下所示,但是当我第一次尝试启动片段时,我就会崩溃。在最初的崩溃之后,如果我试图再次启动这个片段,它就会加载得很好。
在尝试启动片段之前,我正在检查模块是否已安装。为什么我还会有第一次撞车?这几乎就像serviceLoader没有完全加载,除非我让应用程序再闲置一秒钟。
splitInstallManager = SplitInstallManagerFactory.create(this)
val request = SplitInstallRequest
.newBuilder()
.addModule("dynamicFragment")
.build()
splitInstallManager.startInstall(request)
.addOnSuccessListener { sessionId ->
if (!splitInstallManager.installedModules.contains("dynamicFragment"))
return@addOnSuccessListener
findViewById<TextView>(R.id.installStatus).text = "Successfully installed dynamic module, sessionId=$sessionId"
val launch = findViewById<Button>(R.id.launchFragmentBtn)
launch.visibility = View.VISIBLE
launch.setOnClickListener {
val serviceLoader = ServiceLoader.load(
DynamicFragmentContract.Provider::class.java,
DynamicFragmentContract.Provider::class.java.classLoader)
val c: DynamicFragmentContract = serviceLoader.iterator().next().get()
val fragment = c as Fragment
supportFragmentManager
.beginTransaction().add(R.id.fragmentContainer, f).commit()2022-03-25 21:06:31.960 18125-18125/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myapp.dynamicfeaturemodulesapp, PID: 18125
java.util.NoSuchElementException
at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:366)
at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:416)
at java.util.ServiceLoader$1.next(ServiceLoader.java:494)
at com.myapp.mylibrary.LibraryActivity.onCreate$lambda-3$lambda-1$lambda-0(LibraryActivity.kt:61)
at com.myapp.mylibrary.LibraryActivity.$r8$lambda$_Qbmh4qCZoH4E5ov5s1Js7ZPauo(Unknown Source:0)
at com.myapp.mylibrary.LibraryActivity$$ExternalSyntheticLambda1.onClick(Unknown Source:2)发布于 2022-03-26 04:55:13
事实证明,splitInstallManager.addOnSuccessListener并不能可靠地反映下载/安装状态。在我将其更改为使用SplitInstallStateUpdatedListener之后,一切都如期而至。
private val splitInstallStateUpdatedListener = SplitInstallStateUpdatedListener { state ->
val names = state.moduleNames().joinToString(" - ")
when (state.status()) {
SplitInstallSessionStatus.DOWNLOADING -> {
// In order to see this, the application has to be uploaded to the Play Store.
findViewById<TextView>(R.id.installStatus).text = "Downloading $names..."
}
SplitInstallSessionStatus.INSTALLED -> {
findViewById<TextView>(R.id.installStatus).text =
"Successfully installed $names dynamic feature module"
onSuccessfullyInstalled()
}
SplitInstallSessionStatus.INSTALLING -> {
findViewById<TextView>(R.id.installStatus).text = "Installing $names..."
}
SplitInstallSessionStatus.FAILED -> {
findViewById<TextView>(R.id.installStatus).text =
"Error: ${state.errorCode()} for module ${state.moduleNames()}"
}
}
}https://stackoverflow.com/questions/71625253
复制相似问题