How do i get my last known location in android?

前端 未结 3 1391
一个人的身影
一个人的身影 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

    First onConnected does not get called immediately. It takes some time depending on various factors. So keep a log statement and check when onConnected is called.

    Also if the device location is turned off then you will never receive any data back. It will be null.

    Also it is not necessary that the google api client will hold your last location irrespective of whether you are connected to internet or not. It might and it might not. It only caches the last location and cache can be cleared anytime by the android OS.

    0 讨论(0)
  • 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:

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    

    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<out String>,
        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


    0 讨论(0)
  • 2020-12-12 05:38

    GetLastLocation is called by the FusedLocationApi and stores the last location based on the last client that had used it. If your app is the first client to use it, it probably will not have gotten the last location as quickly as you call your "OnConnected()" function.

    Here you have some potential options:

    1. Create A Checking Thread
    You could implement a thread that checks for the last known location every X amount of seconds. Then, regardless of whether or not your app was the first to launch, you will eventually receive the last location.
    2. Implement Location Listening
    You could also implement Location Listening in your activity and update your location every time the OnLocationChanged event is fired.

    0 讨论(0)
提交回复
热议问题