gpt4 book ai didi

android - 创建自定义 ActivityResultContract 以请求位置权限

转载 作者:行者123 更新时间:2023-12-05 03:17:48 24 4
gpt4 key购买 nike

我想创建一个自定义 ActivityResultContract 来请求具有自定义响应的粗略和精细位置。

class LocationPermission : ActivityResultContract<Void?, LocationPermissionResult>() {
override fun createIntent(context: Context, input: Array<String>): Intent {
val requestPermissions = arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
)

return Intent(ActivityResultContracts.RequestMultiplePermissions.ACTION_REQUEST_PERMISSIONS)
.putExtra(ActivityResultContracts.RequestMultiplePermissions.EXTRA_PERMISSIONS, requestPermissions)
}

...
}

从 Activity 中调用它:

private val reportLocationIntent = registerForActivityResult(LocationPermission()) { result ->
}

...reportLocationIntent.launch()

然而,这样做时永远不会调用 createIntent。我做错了什么?

最佳答案

您的相关代码存在编译错误,但这种方法似乎有效。我真的不知道问题的“自定义响应”应该是什么,所以我根据您的问题创建了一个名为 class LocationPermissionResult(val granted: Boolean) 的类。它主要是从 ActivityResultContracts 的 RequestMultiplePermissions 编译而来。

在API 30和API 33模拟器上测试,权限对话框打开,返回结果也是正确的。 (确保权限已添加到 AndroidManifest.xml)

这是源代码:

class LocationPermission : ActivityResultContract<Void?, LocationPermissionResult>() {

private val permissions = arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
)

override fun createIntent(context: Context, input: Void?): Intent {
return Intent(ActivityResultContracts.RequestMultiplePermissions.ACTION_REQUEST_PERMISSIONS).putExtra(
ActivityResultContracts.RequestMultiplePermissions.EXTRA_PERMISSIONS, permissions)
}

override fun getSynchronousResult(context: Context,
input: Void?): SynchronousResult<LocationPermissionResult>? {
val allGranted = permissions.all { permission ->
ContextCompat.checkSelfPermission(
context,
permission
) == PackageManager.PERMISSION_GRANTED
}
return if (allGranted) {
SynchronousResult(LocationPermissionResult(true))
} else null
}

override fun parseResult(resultCode: Int, intent: Intent?): LocationPermissionResult {
if (resultCode != Activity.RESULT_OK) return LocationPermissionResult(false)
if (intent == null) return LocationPermissionResult(false)
val grantResults = intent.getIntArrayExtra(
ActivityResultContracts.RequestMultiplePermissions.EXTRA_PERMISSION_GRANT_RESULTS)
return LocationPermissionResult(grantResults?.all { it == PackageManager.PERMISSION_GRANTED } == true)
}
}

class LocationPermissionResult(val granted: Boolean)

关于android - 创建自定义 ActivityResultContract 以请求位置权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73913965/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com