Get location android Kotlin

前端 未结 6 1678
傲寒
傲寒 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:57

    Get location with address in android kotlin

    Add this line in dependencies

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

    Add this in AndroidManifest

    
    
    
    
    

    Copy this below code in your class

    class MainActivity : AppCompatActivity() {
    
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private lateinit var locationRequest: LocationRequest
    private lateinit var locationCallback: LocationCallback
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)
        /*Check location*/
        checkLocation()
    }
    
    private fun checkLocation(){
        val manager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            showAlertLocation()
        }
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        getLocationUpdates()
    }
    
    private fun showAlertLocation() {
        val dialog = AlertDialog.Builder(this)
        dialog.setMessage("Your location settings is set to Off, Please enable location to use this application")
        dialog.setPositiveButton("Settings") { _, _ ->
            val myIntent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
            startActivity(myIntent)
        }
        dialog.setNegativeButton("Cancel") { _, _ ->
            finish()
        }
        dialog.setCancelable(false)
        dialog.show()
    }
    
    private fun getLocationUpdates() {
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        locationRequest = LocationRequest()
        locationRequest.interval = 50000
        locationRequest.fastestInterval = 50000
        locationRequest.smallestDisplacement = 170f //170 m = 0.1 mile
        locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY //according to your app
        locationCallback = object : LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult?) {
                locationResult ?: return
                if (locationResult.locations.isNotEmpty()) {
                    /*val location = locationResult.lastLocation
                    Log.e("location", location.toString())*/
                    val addresses: List
    ? val geoCoder = Geocoder(applicationContext, Locale.getDefault()) addresses = geoCoder.getFromLocation( locationResult.lastLocation.latitude, locationResult.lastLocation.longitude, 1 ) if (addresses != null && addresses.isNotEmpty()) { val address: String = addresses[0].getAddressLine(0) val city: String = addresses[0].locality val state: String = addresses[0].adminArea val country: String = addresses[0].countryName val postalCode: String = addresses[0].postalCode val knownName: String = addresses[0].featureName Log.e("location", "$address $city $state $postalCode $country $knownName") } } } } } // 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() }}

    Run your code and check the log, Happy Coding

提交回复
热议问题