Jetpack Compose:从 Composable 函数启动 ActivityResultContract 请求

nba*_*man 10 android android-jetpack android-jetpack-compose registerforactivityresult

从 的1.2.0-beta01开始androidx.activity:activity-ktx,不能再launch使用创建的请求Activity.registerForActivityResult(),如上面“行为更改”下的链接中突出显示的那样,并在此处Google 问题中看到

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

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

可以通过创建 custom 来解决这个问题ActivityResultContract,它在启动时接受回调。但是,这意味着几乎没有任何内置功能ActivityResultContracts可以与 Jetpack Compose 一起使用。

TL; 博士

应用程序如何ActivityResultsContract@Composable函数发起请求?

vik*_*mar 15

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

声明您的发射意图

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

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

 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))
    }
Run Code Online (Sandbox Code Playgroud)

#googlesignin


ame*_*ter 12

从 开始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())
}
Run Code Online (Sandbox Code Playgroud)


ian*_*ake 10

Activity Result 有两个 API 界面:

  • 核心ActivityResultRegistry。这才是真正的底层工作。
  • 一个方便的接口ActivityResultCallerComponentActivityFragment实现将 Activity Result 请求与 Activity 或 Fragment 的生命周期联系起来

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

相反,您应该直接使用ActivityResultRegistryAPI,调用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
}

Run Code Online (Sandbox Code Playgroud)

然后可以通过代码在您自己的 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())
}
Run Code Online (Sandbox Code Playgroud)

  • @ianhanniballake 我不知道为什么,但事实证明这个解决方案极其不可靠且不可预测。似乎 `currentOnResult.value(it)` 似乎只是*有时*被调用,我不知道为什么。这非常令人沮丧。 (2认同)

HRJ*_*HRJ 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())
    }
}
Run Code Online (Sandbox Code Playgroud)

(来自此处给出的示例)


Nag*_*obi 5

对于那些没有按照 @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
}
Run Code Online (Sandbox Code Playgroud)