首页 > 解决方案 > 位置开关后存在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,但没有帮助。设置后如何返回我的应用程序?

谢谢扎梅克

标签: androidandroid-permissions

解决方案


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

我在小米设备上检查过。也许这应该是问题...

谢谢,扎梅克


推荐阅读