23

1.2.0 -beta01开始,androidx.activity:activity-ktx无法再launch使用.Activity.registerForActivityResult()

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

可以通过以下方式解决新行为,例如,在 ActivityonCreate函数外部实例化后,将注册 Activity 结果的类沿链传递,然后在Composable. 但是,无法通过这种方式注册要在完成后执行的回调。

可以通过创建 custom 来解决这个问题ActivityResultContract,它在启动时会进行回调。但是,这意味着几乎所有内置程序ActivityResultContracts都不能与 Jetpack Compose 一起使用。

TL;博士

应用程序如何ActivityResultsContract@Composable函数启动请求?

4

5 回答 5

32

从 开始androidx.activity:activity-compose:1.3.0-alpha06registerForActivityResult()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())
}
于 2021-04-19T06:33:03.430 回答
10

Activity Result 有两个 API 界面:

  • 核心ActivityResultRegistry。这实际上是底层工作。
  • 其中的便利接口和ActivityResultCaller实现将 Activity Result 请求与 Activity 或 Fragment 的生命周期联系起来ComponentActivityFragment

Composable 与 Activity 或 Fragment 具有不同的生命周期(例如,如果您从层次结构中删除 Composable,它应该自行清理),因此使用ActivityResultCaller诸如此类的 APIregisterForActivityResult()绝不是正确的做法。

相反,您应该直接使用ActivityResultRegistryAPI,直接register()调用unregister()rememberUpdatedState()这最好与和配对,DisposableEffect以创建一个registerForActivityResult与 Composable 一起使用的版本:

@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())
}
于 2020-11-06T23:04:52.820 回答
8

自此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())
    }
}

(来自此处给出的示例)

于 2021-03-14T19:21:12.830 回答
3

对于那些在我的情况下没有通过@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
}
于 2020-12-16T12:23:55.250 回答
0

添加以防有人开始新的外部意图。就我而言,我想在点击 jetpack compose 中的按钮时启动 google 登录提示。

宣布你的意图发射

val startForResult =
    rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        if (result.resultCode == Activity.RESULT_OK) {
            val intent = result.data
            //do something here
        }
    }

启动您的新活动或任何意图。

 Button(
        onClick = {
            //important step
            startForResult.launch(googleSignInClient?.signInIntent)
        },
        modifier = Modifier
            .fillMaxWidth()
            .padding(start = 16.dp, end = 16.dp),
        shape = RoundedCornerShape(6.dp),
        colors = ButtonDefaults.buttonColors(
            backgroundColor = Color.Black,
            contentColor = Color.White
        )
    ) {
        Image(
            painter = painterResource(id = R.drawable.ic_logo_google),
            contentDescription = ""
        )
        Text(text = "Sign in with Google", modifier = Modifier.padding(6.dp))
    }

#google登录

于 2021-12-31T11:07:22.693 回答