How do i get my last known location in android?

前端 未结 3 1396
一个人的身影
一个人的身影 2020-12-12 05:24

I am using google play services to get my last location. the project is working fine without force closing, however, it never gets any location. i assume it doesn\'t require

3条回答
  •  长情又很酷
    2020-12-12 05:37

    NOTE: I am writing this answer in the year 2020 and the simplest way to get the current location/the last known location (both are more or less the same) is using "FusedLocationProviderClient".

    First, we need to implement the following google play service dependency for location in our build.gradle file:

    implementation com.google.android.gms:play-services-location:17.0.0
    

    Add the permissions in the manifest file:

    
    
    

    Then declare some variable and constant in our activity as below:

    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private val PERMISSIONS_REQUEST_LOCATION = 1
    

    Then in onCreate, get the FusedLocationProviderClient from LocationServices:

    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
    

    And then we can use the below "getCurrentLocation()" method to ask the location permissions from the user and get the current location once user allows the permissions:

    private fun getCurrentLocation() {
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION
                ),
                PERMISSIONS_REQUEST_LOCATION
            )
            return
        }
        fusedLocationClient.lastLocation
            .addOnSuccessListener { location : Location? ->
                Toast.makeText(this, "Latitude: ${location?.latitude}, Longitude: ${location?.longitude}", Toast.LENGTH_SHORT).show()
            }
    }
    
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array,
        grantResults: IntArray
    ) {
        if (requestCode == PERMISSIONS_REQUEST_LOCATION) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                getCurrentLocation()
            } else {
                Toast.makeText(this, "You need to allow the permissions for Location", Toast.LENGTH_SHORT).show()
                return
            }
        }
    }
    

    For more details please refer: https://developer.android.com/training/location/retrieve-current


提交回复
热议问题