从androidx.activity:activity-ktx
的 1.2.0-beta01 开始,人们无法再launch
使用Activity.registerForActivityResult()
创建的请求,如上面"行为更改"下的链接中突出显示的那样,并在 Google 问题中看到此处。
应用程序现在应该如何通过@Composable
函数启动此请求?以前,应用可以使用Ambient
将MainActivity
的实例沿链向下传递,然后轻松启动请求。
例如,在 Activity 的onCreate
函数外部实例化后,将注册活动结果的类沿链向下传递,然后在Composable
中启动请求。但是,注册要在完成后执行的回调不能以这种方式完成。
可以通过 创建自定义ActivityResultContract
,在启动时接受回调。但是,这意味着几乎没有内置ActivityResultContracts
可以与Jetpack Compose一起使用。
TL;博士
应用如何从@Composable
函数启动ActivityResultsContract
请求?
自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())
}
活动结果有两个 API 图面:
- 核心
ActivityResultRegistry
.这就是实际执行底层工作的内容。 ComponentActivity
和Fragment
实现的ActivityResultCaller
中的便捷界面,将活动结果请求与活动或片段的生命周期联系起来
可组合对象的生存期与活动或片段不同(例如,如果从层次结构中删除可组合对象,它应该自行清理),因此使用ActivityResultCaller
API (如registerForActivityResult()
)从来都不是正确的做法。
相反,您应该直接使用ActivityResultRegistry
API,直接调用register()
和unregister()
。最好将其与rememberUpdatedState()
和DisposableEffect
配对,以创建与可组合对象一起使用的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
}
然后可以通过代码在您自己的可组合中使用它,例如:
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())
}
截至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())
}
}
(来自这里给出的样本)
如果有人开始新的外部意图,则添加。就我而言,我想在单击喷气背包组合中的按钮时启动谷歌登录提示。
声明您的意向启动
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))
}
#googlesignin
对于那些没有获得@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
}
对向用户请求权限的方法(例如 PermissionState.launchPermissionRequest())的调用需要从不可组合的范围调用。
val scope = rememberCoroutineScope()
if (!permissionState.status.isGranted) {
scope.launch {
permissionState.launchPermissionRequest()
}
}
以下是在撰写中启动和选择图像的方法:
@Composable
fun ChangeProfilePictureScreen(viewModel: ChangeProfilePictureViewModel = viewModel()) {
val pickMedia = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri: Uri? ->
if (uri != null) {
Log.d("PhotoPicker", "Selected URI: $uri")
} else {
Log.d("PhotoPicker", "No media selected")
}
}
Button(
text = "Select image",
onClick = {
pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.SingleMimeType(mimeType = "image/*")))
}
)
}