android Jetpack组成:从Composable函数启动ActivityResultContract请求

b4qexyjb  于 2023-05-05  发布在  Android
关注(0)|答案(6)|浏览(314)

androidx.activity:activity-ktx的1.2.0-beta 01开始,人们不能再launch使用Activity.registerForActivityResult()创建的请求,如上面的链接中“行为更改”和Google issue here中所示。
应用程序现在应该如何通过@Composable函数启动此请求?以前,应用程序可以通过使用AmbientMainActivity的示例向下传递,然后轻松启动请求。
新的行为可以通过以下方式来解决,例如,在Activity的onCreate函数外部示例化后,将注册Activity结果的类向下传递,然后在Composable中启动请求。但是,注册完成后要执行的回调不能通过这种方式完成。
可以通过创建自定义的ActivityResultContract来解决这个问题,它在启动时接受一个回调。然而,这意味着几乎没有内置的ActivityResultContracts可以与Jetpack Compose一起使用。

TL;DR

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

8cdiaqws

8cdiaqws1#

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())
}
wmomyfyw

wmomyfyw2#

“活动结果”有两个API图面:

  • 核心ActivityResultRegistry。这就是实际做底层工作的东西。
  • ComponentActivityFragment实现的ActivityResultCaller中的一个便利接口,用于将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())
}
ffscu2ro

ffscu2ro3#

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

(From给定样本here

9rygscc1

9rygscc14#

如果有人开始新的外部意图,则添加。在我的例子中,我想在jetpack compose中点击按钮时启动一个谷歌登录提示。
宣布你的发射意图

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

启动新活动或任何Intent。

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

ecfdbz9o

ecfdbz9o5#

对于那些没有得到@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
}
ijxebb2r

ijxebb2r6#

对向用户请求权限的方法的调用(例如launchPermissionRequest())需要从不可组合的作用域调用。

val scope = rememberCoroutineScope()
if (!permissionState.status.isGranted) {
    scope.launch {
         permissionState.launchPermissionRequest()
    }
}

相关问题