如何使用FusedLocationProviderClient连续跟踪位置

时间:2019-08-26 02:43:57

标签: kotlin-android-extensions

我想使用FusedLocationProviderClient持续跟踪在Kotlin开发的android手机上的位置,但是在启动时崩溃了

我已经按照官方文档成功找到了最后一个已知的位置,但是在“更改位置设置”和“接收位置更新”中却失败了。以下是我的代码。我不知道该用什么代替。谢谢。

private const val MY_PERMISSIONS_REQUEST_LOCATION = 1

class MainActivity : AppCompatActivity() {

    private lateinit var fusedLocationClient: FusedLocationProviderClient

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (!checkPermission(permissions)) {

            // permission request dialog
            ActivityCompat.requestPermissions(this,
                permissions, MY_PERMISSIONS_REQUEST_LOCATION)

        } else {

            permissionGrantedView()
        }
    }

    private fun checkPermission(permissions: Array<String>): Boolean {
        var anyPermissionGranted = false
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(this, permission)
                == PackageManager.PERMISSION_GRANTED)
                anyPermissionGranted = true
        }
        return anyPermissionGranted
    }

    // Handling user responds to the permission request dialog
    override fun onRequestPermissionsResult(requestCode: Int,
                                            permissions: Array<String>, grantResults: IntArray) {

        if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
            // If request is cancelled, the result arrays are empty.

            // permission granted
            permissionGrantedView()

        } else {

            // permission denied
            permissionDeniedView()
        }
    }

    private fun permissionGrantedView() {
        Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show()
        btn_get_last_location.setOnClickListener { getLastLocation() }
    }

    private fun permissionDeniedView() {
        Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
        btn_get_last_location.isEnabled = false
    }

    private fun getLastLocation() {

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

        if (checkPermission(permissions)) {

            fusedLocationClient.lastLocation.addOnSuccessListener { location: Location? ->

                if (location == null) {
                    Toast.makeText(this, "Location null", Toast.LENGTH_SHORT).show()
                } else {
                    text_last_location.append("${Calendar.getInstance().time}\n")
                    text_last_location.append("${location.latitude}\n")
                    text_last_location.append("${location.longitude}\n")
                }
            }
        }
    }

    fun createLocationRequest() {
        val locationRequest = LocationRequest.create()?.apply {
            interval = 10000
            fastestInterval = 5000
            priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        }

      val builder = LocationSettingsRequest.Builder().addLocationRequest(locationRequest)

      val client: SettingsClient = LocationServices.getSettingsClient(this)
            val task: Task<LocationSettingsResponse> = client.checkLocationSettings(builder.build())

      task.addOnSuccessListener { locationSettingsResponse ->
          // All location settings are satisfied. The client can initialize
          // location requests here.
          // ...
      }

      task.addOnFailureListener { exception ->
          if (exception is ResolvableApiException){
              // Location settings are not satisfied, but this can be fixed
              // by showing the user a dialog.
              try {
                  // Show the dialog by calling startResolutionForResult(),
                  // and check the result in onActivityResult().
                  exception.startResolutionForResult(this@MainActivity,
                          REQUEST_CHECK_SETTINGS)
              } catch (sendEx: IntentSender.SendIntentException) {
                  // Ignore the error.
              }
          }
      }
    }
}

有许多未解决的参考,我也不知道本节的结果。

0 个答案:

没有答案