Jetpack Compose:从 Composable 函数启动 ActivityResultContract 请求
Jetpack Compose: Launch ActivityResultContract request from Composable function
截至 1.2.0-beta01 of androidx.activity:activity-ktx
, one can no longer launch
the request created using Activity.registerForActivityResult()
, as highlighted in the above link under "Behavior Changes" and seen in the Google issue here。
应用程序现在应该如何通过 @Composable
函数启动此请求?以前,应用程序可以通过使用 Ambient
将 MainActivity
的实例传递到链下,然后轻松启动请求。
新行为可以通过以下方式解决,例如,在 Activity 的 onCreate
函数,然后在 Composable
中启动请求。但是,注册完成后执行的回调不能通过这种方式完成。
可以通过创建自定义 ActivityResultContract
来解决这个问题,它在启动时接受回调。但是,这意味着几乎 none 的内置 ActivityResultContracts
可以与 Jetpack Compose 一起使用。
TL;DR
应用程序如何从 @Composable
函数启动 ActivityResultsContract
请求?
Activity 结果有两个 API 面:
- 核心
ActivityResultRegistry
。这才是真正的底层工作。
ActivityResultCaller
中 ComponentActivity
和 Fragment
实现的便捷接口,将 Activity 结果请求与 Activity 或 Fragment[ 的生命周期联系起来=38=]
可组合项的生命周期不同于 Activity 或片段(例如,如果您从层次结构中删除可组合项,它应该自行清理),因此使用 ActivityResultCaller
[=诸如 registerForActivityResult()
之类的 45=] 从来都不是正确的做法。
相反,您应该直接使用 ActivityResultRegistry
API,调用 register()
and unregister()
directly. This is best paired with the rememberUpdatedState()
and 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())
}
对于那些没有通过@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
}
从 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 )
自 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())
}
添加以防有人开始新的外部意图。就我而言,我想在点击 Jetpack Compose 中的按钮时启动 google 登录提示。
声明您的启动意图
val startForResult =
rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
val intent = result.data
//do something here
}
}
启动您的新 activity 或任何意图。
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登录
截至 1.2.0-beta01 of androidx.activity:activity-ktx
, one can no longer launch
the request created using Activity.registerForActivityResult()
, as highlighted in the above link under "Behavior Changes" and seen in the Google issue here。
应用程序现在应该如何通过 @Composable
函数启动此请求?以前,应用程序可以通过使用 Ambient
将 MainActivity
的实例传递到链下,然后轻松启动请求。
新行为可以通过以下方式解决,例如,在 Activity 的 onCreate
函数,然后在 Composable
中启动请求。但是,注册完成后执行的回调不能通过这种方式完成。
可以通过创建自定义 ActivityResultContract
来解决这个问题,它在启动时接受回调。但是,这意味着几乎 none 的内置 ActivityResultContracts
可以与 Jetpack Compose 一起使用。
TL;DR
应用程序如何从 @Composable
函数启动 ActivityResultsContract
请求?
Activity 结果有两个 API 面:
- 核心
ActivityResultRegistry
。这才是真正的底层工作。 ActivityResultCaller
中ComponentActivity
和Fragment
实现的便捷接口,将 Activity 结果请求与 Activity 或 Fragment[ 的生命周期联系起来=38=]
可组合项的生命周期不同于 Activity 或片段(例如,如果您从层次结构中删除可组合项,它应该自行清理),因此使用 ActivityResultCaller
[=诸如 registerForActivityResult()
之类的 45=] 从来都不是正确的做法。
相反,您应该直接使用 ActivityResultRegistry
API,调用 register()
and unregister()
directly. This is best paired with the rememberUpdatedState()
and 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())
}
对于那些没有通过@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
}
从 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 )
自 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())
}
添加以防有人开始新的外部意图。就我而言,我想在点击 Jetpack Compose 中的按钮时启动 google 登录提示。
声明您的启动意图
val startForResult =
rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
val intent = result.data
//do something here
}
}
启动您的新 activity 或任何意图。
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登录