Android Result Api不能在生命周期onStart及之后注册的解决办法

现在Activity的startActivityForResult废弃了,Google建议我们使用Activity Result Api.

然而这个Activity Result Api坑倒是不少

比如在使用

    def activity_version = "1.2.2"
    implementation "androidx.activity:activity:$activity_version"
    implementation "androidx.activity:activity-ktx:$activity_version"
    implementation "androidx.fragment:fragment:$activity_version"

可能会导致

java.lang.IllegalArgumentException: Can only use lower 16 bits for requestCode

要将版本升到1.3.0之后才行

我寻思着干脆将版本直接升到最高吧1.5.0好了,然而升到1.5.0又会导致构建版本太低的项目中报错......

无语......

算了就用1.3.0了.

回归我们的主题,Android Result Api必须在Activity 生命周期onStart之前注册,也就是基本上我们必须在onCreate的时候注册

    val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        Log.d(TAG, "get activity result")
    }

然后在需要使用的时候再launch

    launcher.launch(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))

如果我们不在onCreate中注册,那么我们launch的时候就会报如下错误然后崩掉

java.lang.IllegalStateException: LifecycleOwner com.yxf.extensions.MainActivity@f8e47f4 is attempting to register while current state is RESUMED. LifecycleOwners must call register before they are STARTED.

这操作就离谱,这和原本的startActivityForResult,然后在onActivityResult里监听有太大区别吗?

这特么不还是得分成两段代码,一点都不优雅好吧.


那么这么不优雅的问题有办法解决吗?

我们先分析下为什么会崩吧,先看看registerForActivityResult都做了什么

    @NonNull
    @Override
    public final  ActivityResultLauncher registerForActivityResult(
            @NonNull final ActivityResultContract contract,
            @NonNull final ActivityResultRegistry registry,
            @NonNull final ActivityResultCallback callback) {
        return registry.register(
                "activity_rq#" + mNextLocalRequestCode.getAndIncrement(), this, contract, callback);
    }
    @NonNull
    public final  ActivityResultLauncher register(
            @NonNull final String key,
            @NonNull final LifecycleOwner lifecycleOwner,
            @NonNull final ActivityResultContract contract,
            @NonNull final ActivityResultCallback callback) {

        Lifecycle lifecycle = lifecycleOwner.getLifecycle();

        if (lifecycle.getCurrentState().isAtLeast(Lifecycle.State.STARTED)) {
            throw new IllegalStateException("LifecycleOwner " + lifecycleOwner + " is "
                    + "attempting to register while current state is "
                    + lifecycle.getCurrentState() + ". LifecycleOwners must call register before "
                    + "they are STARTED.");
        }

        final int requestCode = registerKey(key);
        LifecycleContainer lifecycleContainer = mKeyToLifecycleContainers.get(key);
        if (lifecycleContainer == null) {
            lifecycleContainer = new LifecycleContainer(lifecycle);
        }
        LifecycleEventObserver observer = new LifecycleEventObserver() {
            @Override
            public void onStateChanged(
                    @NonNull LifecycleOwner lifecycleOwner,
                    @NonNull Lifecycle.Event event) {
                if (Lifecycle.Event.ON_START.equals(event)) {
                    mKeyToCallback.put(key, new CallbackAndContract<>(callback, contract));
                    //......
                } else if (Lifecycle.Event.ON_STOP.equals(event)) {
                    mKeyToCallback.remove(key);
                } else if (Lifecycle.Event.ON_DESTROY.equals(event)) {
                    unregister(key);
                }
            }
        };
        lifecycleContainer.addObserver(observer);
        //......
        return new ActivityResultLauncher() {
            //......
        };
    }

可以看到在register的时候,在最前面就先判断了当前生命周期,如果生命周期不在STARTED之前就会直接抛异常......

然而讲道理,它非要我们在onCreate里注册的原因不过是它需要在Activity生命周期为onStart的时候执行这么一个操作

mKeyToCallback.put(key, new CallbackAndContract<>(callback, contract));

主要是存储一个回调接口.

当然在onStart时还包含了mParsedPendingResultsmPendingResults的处理,不过这两个处理主要如果Activity 触发了onStop,则将结果回调从onActivityResult延时到Activity重新onStart的时候触发.不过这里我不是很理解延迟回调到onStart的意义是什么,如果有知道的大佬希望可以指点一二.

回到主题,也就是说,为了以上操作,直接就让我们不能在onStart之后注册了,感觉就挺离谱的......

不过话说回来ActivityResultRegistry源码中其实也考虑了不用生命周期的注册方式,注册过程不会抛异常,ActivityResultRegistry的第二个注册方法如下

    @NonNull
    public final  ActivityResultLauncher register(
            @NonNull final String key,
            @NonNull final ActivityResultContract contract,
            @NonNull final ActivityResultCallback callback) {
        final int requestCode = registerKey(key);
        mKeyToCallback.put(key, new CallbackAndContract<>(callback, contract));
        //......
        return new ActivityResultLauncher() {
            //......
        };
    }

这个方法挺好的,有什么需要处理的直接就处理了.不过因为没有监听Activity的生命周期变化,如果不在不需要的时候解除注册可能会导致Activity内存泄漏.

我们可以尝试借助第二个方法来实现Result Api的即时注册和即时使用,方法如下

private val nextLocalRequestCode = AtomicInteger()

fun  FragmentActivity.startContractForResult(
    contract: ActivityResultContract,
    input: I,
    callback: ActivityResultCallback
) {
    val key = "activity_rq_for_result#${nextLocalRequestCode.getAndIncrement()}"
    val registry = activityResultRegistry
    var launcher: ActivityResultLauncher? = null
    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 {
        launcher?.unregister()
        lifecycle.removeObserver(observer)
        callback.onActivityResult(it)
    }
    launcher = registry.register(key, contract, newCallback)
    launcher.launch(input)
}

通过以上代码我们就能优雅的实现在onStart之后依然能注册Result Api, 而且将注册和launch的过程结合提高代码的紧凑性.

    activity.startContractForResult(ActivityResultContracts.StartActivityForResult(), Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)) {
        if (it.resultCode == Activity.RESULT_OK) {
            Log.d(TAG, "get activity result successfully")
        } else {
            Log.w(TAG, "get activity result failed")
        }
    }

如果你像我一样依然还在使用RxJava,为此我觉得还可以更优雅的将此装封到RxJava扩展中,代码如下

internal class ObservableStartContractForResult(
    private var fragmentActivity: FragmentActivity?,
    private val contract: ActivityResultContract,
    private val input: I
) : Observable() {

    override fun subscribeActual(observer: Observer) {
        observer.onSubscribe(StartContractForResultObserver(observer, fragmentActivity, contract, input))
        fragmentActivity = null
    }

    private inner class StartContractForResultObserver(
        private val downStream: Observer,
        private var activity: FragmentActivity?,
        private val contract: ActivityResultContract,
        private val input: I
    ) : AtomicReference(), Disposable {


        private var launcher: ActivityResultLauncher? = null

        val observer = LifecycleEventObserver { _, event ->
            if (Lifecycle.Event.ON_DESTROY == event) {
                releaseAll()
                downStream.onError(LifecycleDestroyedException())
            }
        }


        init {
            runOnMainThreadSync {
                val key = "activity_rq_for_result#${nextLocalRequestCode.getAndIncrement()}"
                val registry = activity!!.activityResultRegistry
                activity!!.lifecycle.addObserver(observer)
                val newCallback = ActivityResultCallback {
                    releaseAll()
                    downStream.onNext(it)
                    downStream.onComplete()
                }
                launcher = registry.register(key, contract, newCallback)
                launcher?.launch(input)
            }
        }

        private fun releaseAll() {
            releaseObserver()
            releaseLauncher()
            releaseActivity()
        }

        private fun releaseActivity() {
            activity = null
        }

        private fun releaseLauncher() {
            launcher?.unregister()
            launcher = null
        }

        private fun releaseObserver() {
            activity?.lifecycle?.removeObserver(observer)
        }


        override fun dispose() {
            if (isDisposed) {
                return
            }
            DisposableHelper.dispose(this)
            runOnMainThread{
                releaseAll()
            }
        }

        override fun isDisposed(): Boolean {
            return get() == DisposableHelper.DISPOSED
        }

    }

}
fun  FragmentActivity.rxStartContractForResult(contract: ActivityResultContract, input: I): Observable {
    return RxJavaPlugins.onAssembly(ObservableStartContractForResult(this, contract, input))
}

如此我们便可以配合RxJava实现极致的优雅.

    activity.rxStartContractForResult(ActivityResultContracts.StartActivityForResult(), Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
        .subscribe {
            Log.d(TAG, "get activity result")
        }

具体源码参见 https://github.com/dqh147258/RxAndroidExtensions


当然,其实以上功能吧,long long ago,就有大佬们通过Fragment实现了......

不过毕竟通过一个不可见的Fragment还是太骚了,也会影响一些关于Fragment数量的逻辑判断

emmmmm, that's all.

你可能感兴趣的:(Android Result Api不能在生命周期onStart及之后注册的解决办法)