Я не могу найти учебник, который использовал сейчас, но смог заставить его работать с помощью следующего кода. Ниже приведен код для будущего одинокого путешественника по переполнению стека.
build.gradle
...
dependencies {
implementation 'com.google.android.gms:play-services-location:17.0.0'
}
...
Androidmanifest.xml
...
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" /> <!-- I think this is required for Android 10 (API 29) + -->
...
class ClassName : AppCompatActivity() {
private lateinit var fusedLocationClient: FusedLocationProviderClient
private val locationCallBack: LocationCallback = object : LocationCallback() {
override fun onLocationResult(p0: LocationResult?) {
val location: Location? = p0?.lastLocation
if(location != null) {
latitude = location.latitude.toString()
longitude = location.longitude.toString()
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
...
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
getLocation()
...
}
private fun getLocation() {
if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
val locationManager: LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
fusedLocationClient.lastLocation.addOnCompleteListener(this) { task ->
val location: Location? = task.result
if(location == null)
requestLocation()
else {
latitude = location.latitude.toString()
longitude = location.longitude.toString()
}
}
}
}
}
private fun requestLocation() {
val locationRequest = LocationRequest()
locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
locationRequest.interval = 0
locationRequest.fastestInterval = 0
locationRequest.numUpdates = 1
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallBack, Looper.myLooper())
}
}