Jetpack Compose构建悬浮窗遇重复类编译错误求助
解决Jetpack Compose悬浮窗构建冲突与代码优化
一、解决Kotlin stdlib重复类构建错误
你遇到的checkDebugDuplicateClasses错误,根源是androidx.lifecycle:lifecycle-runtime-ktx:2.6.0依赖的Kotlin stdlib版本(1.8.10)与项目中已有的kotlin-stdlib-jdk7-1.7.21、kotlin-stdlib-jdk8-1.7.21版本冲突,可通过以下两种方式解决:
方式1:统一项目Kotlin版本
在项目根目录的build.gradle(或build.gradle.kts)中,将Kotlin插件版本和stdlib版本统一为1.8.10:
// 项目级build.gradle buildscript { ext { kotlin_version = "1.8.10" } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } }
同时在模块级build.gradle中替换旧的stdlib依赖,确保版本统一:
// 模块级build.gradle implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
方式2:排除Lifecycle依赖中的冲突stdlib
如果无法统一Kotlin版本,可在添加Lifecycle依赖时直接排除旧版本的stdlib:
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.6.0") { exclude group: "org.jetbrains.kotlin", module: "kotlin-stdlib-jdk7" exclude group: "org.jetbrains.kotlin", module: "kotlin-stdlib-jdk8" }
二、优化Jetpack Compose悬浮窗代码
你当前的代码存在冗余逻辑(手动管理Recomposer等),以下是简化后的实现,同时保证Lifecycle管理的正确性:
1. 简化自定义LifecycleOwner实现
internal class MyLifecycleOwner : SavedStateRegistryOwner { private val lifecycleRegistry = LifecycleRegistry(this) private val savedStateRegistryController = SavedStateRegistryController.create(this) override val savedStateRegistry: SavedStateRegistry get() = savedStateRegistryController.savedStateRegistry override val lifecycle: Lifecycle get() = lifecycleRegistry fun onCreate() { savedStateRegistryController.performRestore(null) lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE) } fun onDestroy() { lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY) } }
2. Service中创建悬浮窗的简化代码
val windowManager = getSystemService(WINDOW_SERVICE) as WindowManager val params = WindowManager.LayoutParams().apply { width = 500 height = 500 type = WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY gravity = Gravity.TOP or Gravity.CENTER_HORIZONTAL format = PixelFormat.TRANSPARENT flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE } val composeView = ComposeView(this).apply { setContent { Text( text = "Hello", color = Color.Black, fontSize = 50.sp, modifier = Modifier.wrapContentSize().background(Color.Green) ) } } // 初始化LifecycleOwner val lifecycleOwner = MyLifecycleOwner() lifecycleOwner.onCreate() // 绑定Lifecycle相关Owner composeView.apply { setViewTreeLifecycleOwner(lifecycleOwner) setViewTreeSavedStateRegistryOwner(lifecycleOwner) setViewTreeViewModelStoreOwner(lifecycleOwner) } windowManager.addView(composeView, params) // Service销毁时必须清理资源 override fun onDestroy() { super.onDestroy() lifecycleOwner.onDestroy() windowManager.removeView(composeView) }
注意:
- 无需手动创建Recomposer和CoroutineScope,
ComposeView.setContent()会自动初始化这些组件- Service销毁时必须移除悬浮窗并调用Lifecycle的
ON_DESTROY事件,避免内存泄漏
内容的提问来源于stack exchange,提问作者one_no_yami_
相关产品推荐
相关产品推荐

