Get location android Kotlin

前端 未结 6 1686
傲寒
傲寒 2020-12-13 07:28

I recently added get location function. When I try to show longitude and latitude, it returns zero.

This my LocationListener class:

inner class Myloc         


        
6条回答
  •  情书的邮戳
    2020-12-13 07:55

    In 2019 Best Offical Solution in Kotlin

    Google API Client/FusedLocationApi are deprecated and Location Manager is not useful at all. So Google prefer Fused Location Provider Using the Google Play services location APIs "FusedLocationProviderClient" is used to get location and its better way for battery saving and accuracy

    Here is sample code in kotlin to get the last known location /one-time location( equivalent to the current location)

     // declare a global variable of FusedLocationProviderClient
        private lateinit var fusedLocationClient: FusedLocationProviderClient
    
    // in onCreate() initialize FusedLocationProviderClient
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(context!!)
    
     /**
         * call this method for receive location
         * get location and give callback when successfully retrieve
         * function itself check location permission before access related methods
         *
         */
        fun getLastKnownLocation() {
                fusedLocationClient.lastLocation
                    .addOnSuccessListener { location->
                        if (location != null) {
                           // use your location object
                            // get latitude , longitude and other info from this
                        }
    
                    }
    
        }
    

    If your app can continuously track the location then you have to receive Receive location updates

    Check the sample for that in kotlin

    // declare a global variable FusedLocationProviderClient
            private lateinit var fusedLocationClient: FusedLocationProviderClient
    
        // in onCreate() initialize FusedLocationProviderClient
            fusedLocationClient = LocationServices.getFusedLocationProviderClient(context!!)
    
    
          // globally declare LocationRequest
            private lateinit var locationRequest: LocationRequest
    
            // globally declare LocationCallback    
            private lateinit var locationCallback: LocationCallback
    
    
            /**
             * call this method in onCreate
             * onLocationResult call when location is changed 
             */
            private fun getLocationUpdates()
            {
    
                    fusedLocationClient = LocationServices.getFusedLocationProviderClient(context!!)
                    locationRequest = LocationRequest()
                    locationRequest.interval = 50000
                    locationRequest.fastestInterval = 50000
                    locationRequest.smallestDisplacement = 170f // 170 m = 0.1 mile
                    locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY //set according to your app function
                    locationCallback = object : LocationCallback() {
                        override fun onLocationResult(locationResult: LocationResult?) {
                            locationResult ?: return
    
                            if (locationResult.locations.isNotEmpty()) {
                                // get latest location 
                                val location =
                                    locationResult.lastLocation
                                // use your location object
                                // get latitude , longitude and other info from this
                            }
    
    
                        }
                    }
            }
    
            //start location updates
            private fun startLocationUpdates() {
                fusedLocationClient.requestLocationUpdates(
                    locationRequest,
                    locationCallback,
                    null /* Looper */
                )
            }
    
            // stop location updates
            private fun stopLocationUpdates() {
                fusedLocationClient.removeLocationUpdates(locationCallback)
            }
    
            // stop receiving location update when activity not visible/foreground
            override fun onPause() {
                super.onPause()
                stopLocationUpdates()
            }
    
            // start receiving location update when activity  visible/foreground
            override fun onResume() {
                super.onResume()
                startLocationUpdates()
            }
    

    Make sure you take care about Mainfaist permission and runtime permission for location

    
    

    and for Gradle add this

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

    For more details follow these official documents

    https://developer.android.com/training/location/retrieve-current

    https://developer.android.com/training/location/receive-location-updates

    https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient

提交回复
热议问题