Get current location Android Kotlin

21,274

Solution 1

Try as follow

Step 1. Put on your AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com....">

    <!-- This line -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application ... />

</manifest>

Step 2. Put it above your location request

import android.Manifest
import android.content.pm.PackageManager
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat

...

fun getLocation() {

    ...

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                PERMISSION_REQUEST_ACCESS_FINE_LOCATION)
        return
    }
    locationManager!!.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0f, locationListener)
}

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    if (requestCode == PERMISSION_REQUEST_ACCESS_FINE_LOCATION) {
        when (grantResults[0]) {
            PackageManager.PERMISSION_GRANTED -> getLocation()
            PackageManager.PERMISSION_DENIED -> //Tell to user the need of grant permission
        }
    }
}

companion object {
    private const val PERMISSION_REQUEST_ACCESS_FINE_LOCATION = 100
}

Solution 2

The LocationManager will throw a SecurityException if the location permission has not been granted.

Information on adding the location permissions to your app can be found here.

Share:
21,274

Related videos on Youtube

G. Lukas
Author by

G. Lukas

Updated on July 14, 2020

Comments

  • G. Lukas
    G. Lukas over 3 years

    I try to get the current Location with GM API in my application (using Android Studio). But if i click the button which triggers the getLocation() funktion, i always end up in the catch{} block and i dont know why. My mobile device is connected for testing.

    Here is the getLocation() Funktion:

    fun getLocation() {
    
        var locationManager = getSystemService(LOCATION_SERVICE) as LocationManager?
    
        var locationListener = object : LocationListener{
            override fun onLocationChanged(location: Location?) {
                var latitute = location!!.latitude
                var longitute = location!!.longitude
    
                Log.i("test", "Latitute: $latitute ; Longitute: $longitute")
    
            }
    
            override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
            }
    
            override fun onProviderEnabled(provider: String?) {
            }
    
            override fun onProviderDisabled(provider: String?) {
            }
    
        }
    
        try {
            locationManager!!.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0f, locationListener)
        } catch (ex:SecurityException) {
            Toast.makeText(applicationContext, "Fehler bei der Erfassung!", Toast.LENGTH_SHORT).show()
        }
    }
    

    Here is the onCreate Funktion:

    class CurrentLocationActivity : AppCompatActivity() {
    
    
    lateinit var mapFragment : SupportMapFragment
    lateinit var googleMap : GoogleMap
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_current_location)
    
        //Karte erstellen
        mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(OnMapReadyCallback {
            googleMap = it
        })
    
    
    
        //OnClickListener um Location zu speichern
        btnGetCurrentLocation.setOnClickListener {
            getLocation()
        }
    }
    
    • Abner Escócio
      Abner Escócio over 5 years
      Check if location permission is granted
    • G. Lukas
      G. Lukas over 5 years
      Somehow I can't check for permission. If i click Alt + Enter and click on add permission check nothing happens. Also if i type in manual, AndroidStudio says in Manifest.permission, that ist a unresolved reference: permission
    • Abner Escócio
      Abner Escócio over 5 years
      Try manually set permission to access location on Settings > Apps > Your App > Info > Permissions. If it work, we will discovery the problem and I will put the solution to you
  • G. Lukas
    G. Lukas over 5 years
    I've noticed that Site, but also if I copy the code I always get the "unresolved reference: permission" in Manifest.permission.ACCESS_FINE_LOCATION
  • pau1adam
    pau1adam over 5 years
    You probably imported java.util.jar.Manifest instead of android.Manifest
  • G. Lukas
    G. Lukas over 5 years
    I still get "unresolved reference: permission" on Manifest.permission.ACCESS_FINE_LOCATION Also I've got "unresolvede reference" on PERMISSION_REQUEST_ACCESS_FINE_LOCATION
  • G. Lukas
    G. Lukas over 5 years
    I have. Here are my Imports: import android.Manifest.permission.ACCESS_FINE_LOCATION import android.content.pm.PackageManager import android.location.Location import android.location.LocationListener import android.location.LocationManager import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.support.v4.content.ContextCompat.checkSelfPermission
  • G. Lukas
    G. Lukas over 5 years
    import android.util.Log import android.widget.Toast import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.LatLng import kotlinx.android.synthetic.main.activity_current_location.* import java.util.jar.Manifest
  • G. Lukas
    G. Lukas over 5 years
    PERMISSION_REQUEST_ACCESS_FINE_LOCATION now works, but "unresolved reference: permission" on Manifest.permission.ACCESS_FINE_LOCATION didnt't disappear.
  • Abner Escócio
    Abner Escócio over 5 years
    Remove this call import java.util.jar.Manifest and it will work
  • G. Lukas
    G. Lukas over 5 years
    Thank you man this worked!! I Imported android.Manifest instead