private val registerForActivityResultNoVerifyLifecycleVersion = AtomicLong(0) // 注册的key的版本,使用原子操作,防止重复 /** * 忽略生命周期注册ActivityResult的launcher。(原生的必须在Activity的onStart之前注册,该方法不受限) * * @author hanliangdong * @since 2024-6-01 */ fun FragmentActivity.registerForActivityResultNoVerifyLifecycle(callBack: ActivityResultCallback<ActivityResult>): ActivityResultLauncher<Intent> { val key = "registerForActivityResultNoVerifyLifecycle#${registerForActivityResultNoVerifyLifecycleVersion.getAndIncrement()}" var launcher: ActivityResultLauncher<Intent>? = null // 添加Activity的生命周期监听,及时移除launcher,防止内存泄露 val observer = object : LifecycleEventObserver { override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { if (Lifecycle.Event.ON_DESTROY == event) { launcher?.unregister() lifecycle.removeObserver(this) } } } lifecycle.addObserver(observer) val newCallback = ActivityResultCallback<ActivityResult> { callBack.onActivityResult(it) launcher?.unregister() } launcher = activityResultRegistry.register(key, ActivityResultContracts.StartActivityForResult(), newCallback) return launcher }
Android中registerForActivityResult如何在oncreate以外生命周期使用
最新推荐文章于 2024-08-15 14:16:14 发布