我有一个应用程序,它应该在启动时检查位置服务是否打开或关闭。我尝试使用
AlerDialog
,并通过 Intent
将用户发送到设置,但它无法按照我的意愿工作。
我改变了方法,因为我想在用户从设置返回后检查位置服务,并写下以下功能:
@Composable
private fun TEST() {
val locationManager =
LocalContext.current.getSystemService(Context.LOCATION_SERVICE) as LocationManager
val locationPermissionLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartActivityForResult(),
onResult = {
Log.i(TAG, "TEST: ${locationManager.isLocationEnabled}")
})
val context = LocalContext.current
LaunchedEffect(key1 = true) {
locationPermissionLauncher.launch(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
}
}
现在,这是个好方法吗? Intent服务结果不能直接注册Activity吧?我该如何正确处理它?
LaunchedEffect 在这种情况下将不起作用,因为当您的应用程序返回前台时,它不会再次触发。相反,您可以观察 Jetpack Compose 中的活动生命周期方法,如下所示:
val lifecycleOwner = LocalLifecycleOwner.current
val lifecycleState by lifecycleOwner.lifecycle.currentStateFlow.collectAsState()
val isPermissionGranted =
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED
if(!isPermissionGranted) {
// setup rememberLauncherForActivityResult
// launch Activity
}
LaunchedEffect(lifecycleState) {
if (lifecycleState == Lifecycle.State.RESUMED ) {
// Activity was resumed. This is called when user returns to App.
// Check here again whether the permission is granted now.
)
}