Issue
I have the problem with getting the LocationManager object. The code should work on all Android API but while my tests I found that LocationManager isn't null only in 25 API.
fun invokeLocalization(): Location? {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val locationManager = ctx.applicationContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
if ( ctx.checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
var bestLocation: Location? = null
for (provider in locationManager.getProviders(true)) {
val location = locationManager.getLastKnownLocation(provider) ?: continue
if (bestLocation == null || location.accuracy < bestLocation.accuracy) bestLocation = location
}
return bestLocation
} else {
(ctx as AddAlertActivity).requestPermissions(arrayOf(LocationManager.GPS_PROVIDER),PackageManager.PERMISSION_GRANTED)
return locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
}
}
return null
}
And my manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.location.gps" />
Premission is enabled for localization in android's settings.
I will be grateful for your help.
Solution
Use FusedLocation API from google which got updated location or last known location
https://developers.google.com/location-context/fused-location-provider/
Answered By - Parth Suthar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.