Jetpack撰写:从Composable函数启动ActivityResultContract请求

时间:2020-11-06 20:32:28

标签: android android-jetpack android-jetpack-compose registerforactivityresult

androidx.activity:activity-ktx的{​​{3}}起,不再可以launch使用Activity.registerForActivityResult()创建的请求,如上面链接“行为更改”下突出显示的内容所示。 1.2.0-beta01

应用程序现在应该如何通过@Composable函数启动此请求?以前,应用程序可以通过使用MainActivityAmbient的实例沿链向下传递,然后轻松启动请求。

可以通过以下方法来解决新行为:例如,在Activity的onCreate函数之外实例化实例之后,将注册活动结果的类向下传递给链,然后在{{1 }}。但是,无法以这种方式注册要在完成后执行的回调。

可以通过创建自定义Composable来解决此问题,该自定义ActivityResultContract在启动时会进行回调。但是,这实际上意味着内置ActivityResultContracts都不能与Jetpack Compose一起使用。

TL; DR

应用如何通过ActivityResultsContract函数启动@Composable请求?

4 个答案:

答案 0 :(得分:8)

androidx.activity:activity-compose:1.3.0-alpha06 起,registerForActivityResult() API 已重命名为 rememberLauncherForActivityResult(),以更好地表明返回的 ActivityResultLauncher 是代表您记住的托管对象。

val result = remember { mutableStateOf<Bitmap?>(null) }
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.TakePicturePreview()) {
    result.value = it
}

Button(onClick = { launcher.launch() }) {
    Text(text = "Take a picture")
}

result.value?.let { image ->
    Image(image.asImageBitmap(), null, modifier = Modifier.fillMaxWidth())
}

答案 1 :(得分:7)

Activity Compose 1.3.0-alpha03 及以后,有一个新的效用函数 registerForActivityResult() 可以简化此过程。

@Composable
fun RegisterForActivityResult() {
    val result = remember { mutableStateOf<Bitmap?>(null) }
    val launcher = registerForActivityResult(ActivityResultContracts.TakePicturePreview()) {
        result.value = it
    }

    Button(onClick = { launcher.launch() }) {
        Text(text = "Take a picture")
    }

    result.value?.let { image ->
        Image(image.asImageBitmap(), null, modifier = Modifier.fillMaxWidth())
    }
}

(来自给定的样本 here

答案 2 :(得分:6)

活动结果具有两个API界面:

  • 核心ActivityResultRegistry。这实际上是基础工作。
  • ActivityResultCaller中的便捷界面,其中实现了ComponentActivityFragment,将Activity Result请求与Activity或Fragment的生命周期相关联

一个Composable的生存期与Activity或Fragment的生存期不同(例如,如果您从层次结构中删除Composable,则它应该在其自身之后进行清理),因此使用ActivityResultCaller API,例如registerForActivityResult()永远都不是正确的事情。

相反,您应该直接使用ActivityResultRegistry API,直接调用register()unregister()。最好与rememberUpdatedState()DisposableEffect配对,以创建可与Composable配合使用的registerForActivityResult版本:

@Composable
fun <I, O> registerForActivityResult(
    contract: ActivityResultContract<I, O>,
    onResult: (O) -> Unit
) : ActivityResultLauncher<I> {
    // First, find the ActivityResultRegistry by casting the Context
    // (which is actually a ComponentActivity) to ActivityResultRegistryOwner
    val owner = ContextAmbient.current as ActivityResultRegistryOwner
    val activityResultRegistry = owner.activityResultRegistry

    // Keep track of the current onResult listener
    val currentOnResult = rememberUpdatedState(onResult)

    // It doesn't really matter what the key is, just that it is unique
    // and consistent across configuration changes
    val key = rememberSavedInstanceState { UUID.randomUUID().toString() }

    // Since we don't have a reference to the real ActivityResultLauncher
    // until we register(), we build a layer of indirection so we can
    // immediately return an ActivityResultLauncher
    // (this is the same approach that Fragment.registerForActivityResult uses)
    val realLauncher = mutableStateOf<ActivityResultLauncher<I>?>(null)
    val returnedLauncher = remember {
        object : ActivityResultLauncher<I>() {
            override fun launch(input: I, options: ActivityOptionsCompat?) {
                realLauncher.value?.launch(input, options)
            }

            override fun unregister() {
                realLauncher.value?.unregister()
            }

            override fun getContract() = contract
        }
    }

    // DisposableEffect ensures that we only register once
    // and that we unregister when the composable is disposed
    DisposableEffect(activityResultRegistry, key, contract) {
        realLauncher.value = activityResultRegistry.register(key, contract) {
            currentOnResult.value(it)
        }
        onDispose {
            realLauncher.value?.unregister()
        }
    }
    return returnedLauncher
}

然后可以通过以下代码在自己的Composable中使用它:

val result = remember { mutableStateOf<Bitmap?>(null) }
val launcher = registerForActivityResult(ActivityResultContracts.TakePicturePreview()) {
    // Here we just update the state, but you could imagine
    // pre-processing the result, or updating a MutableSharedFlow that
    // your composable collects
    result.value = it
}

// Now your onClick listener can call launch()
Button(onClick = { launcher.launch() } ) {
    Text(text = "Take a picture")
}

// And you can use the result once it becomes available
result.value?.let { image ->
    Image(image.asImageAsset(),
        modifier = Modifier.fillMaxWidth())
}

答案 3 :(得分:1)

对于那些在我的案例中没有使用@ianhanniballake提供的要点取回结果的人,returnedLauncher实际上捕获了realLauncher的已处置值。

因此,尽管删除间接层应该可以解决此问题,但这绝对不是实现此目的的最佳方法。

这是更新的版本,直到找到更好的解决方案为止:

@Composable
fun <I, O> registerForActivityResult(
    contract: ActivityResultContract<I, O>,
    onResult: (O) -> Unit
): ActivityResultLauncher<I> {
    // First, find the ActivityResultRegistry by casting the Context
    // (which is actually a ComponentActivity) to ActivityResultRegistryOwner
    val owner = AmbientContext.current as ActivityResultRegistryOwner
    val activityResultRegistry = owner.activityResultRegistry

    // Keep track of the current onResult listener
    val currentOnResult = rememberUpdatedState(onResult)

    // It doesn't really matter what the key is, just that it is unique
    // and consistent across configuration changes
    val key = rememberSavedInstanceState { UUID.randomUUID().toString() }

    // TODO a working layer of indirection would be great
    val realLauncher = remember<ActivityResultLauncher<I>> {
        activityResultRegistry.register(key, contract) {
            currentOnResult.value(it)
        }
    }

    onDispose {
        realLauncher.unregister()
    }
    
    return realLauncher
}