android - 位置开关后存在android应用程序
问题描述
我需要在我的应用程序中使用位置,并在每个 onResume 中检查位置。当位置关闭时,我尝试使用以下方式打开它:
val lm = getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (!LocationManagerCompat.isLocationEnabled(lm)) {
val intent = Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(intent)
return
}
当这个活动完成时,我的应用程序退出了。我尝试了 startActivityForResult,但没有帮助。设置后如何返回我的应用程序?
谢谢扎梅克
解决方案
override fun onResume() {
super.onResume()
checkLocation()
}
private fun checkLocation() {
val builder = LocationSettingsRequest.Builder()
.addLocationRequest(LocationRequest().apply {
interval = 10000
fastestInterval=5000
priority=LocationRequest.PRIORITY_LOW_POWER
})
val settingsClient = LocationServices.getSettingsClient(this)
val task : Task<LocationSettingsResponse> = settingsClient.checkLocationSettings(builder.build())
task.addOnSuccessListener {
model.start()
}
task.addOnFailureListener{
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION), REQUEST_LOCATION)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray) {
when(requestCode) {
REQUEST_LOCATION -> locationResult(grantResults)
}
}
private fun locationResult(grantResults: IntArray) {
if (grantResults[0]==PackageManager.PERMISSION_GRANTED) {
val lm = getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (!LocationManagerCompat.isLocationEnabled(lm)) {
val intent = Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(intent)
return
}
model.start()
return
}
exitApplication()
}
我在小米设备上检查过。也许这应该是问题...
谢谢,扎梅克
推荐阅读
- xcode - 运行 git status 时,Mojave 更新后发生以下错误:“xcrun: error: invalid active developer path”
- c# - 如何删除 2 个分隔符之间的字符?
- android - 地理位置问题?
- php - 如何使用 Mailgun 和 PHP API 发送电子邮件?
- javascript - onChange of
- c# - 为标题标题更新 WPF 中的多个 DataGrid
- node.js - 如何从移动应用程序中的私有 api 获取背景的即时更改?
- python - 从路径列表转换为 Flare json 格式?
- css - 如何创建针对智能手机的 CSS
- c# - Sonarqube 中的“此项目为空”错误