Reputation: 15
I have successfully used FusedLocation to get devices last known location before, but I am uncertain why it isn't working in this context.
I have tested it on a physical device, as well as an emulated device.
I implemented play-services, and stated the required permissions in the manifest. I have also checked device permissions for my app, enabled location, and have used Google Maps insure there is a last known location.
I declareprivate FusedLocationProviderClient fusedLocationClient;
in my MainActivity Class.
In Main Activity onCreate(): FusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
Now I am trying to retrieve the last known location from when the user selects an item from an options menu.
if(id == R.id.action_GPS){
fusedLocationClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if(location != null) {
Geocoder gcd = new Geocoder(context, Locale.getDefault());
try {
List<Address> adrs = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
}
}
After debugging over 'fusedLocationClient.getLastLocation()..." it skips to the end, and never reaches the onSuccess method. Why could this be failing?
Upvotes: 1
Views: 1736
Reputation: 156
you can check if GPS is active using
val client = LocationServices.getSettingsClient(this)
val task = client.checkLocationSettings(builder.build())
task.addOnSuccessListener {
//GPS is ON
}
task.addOnFailureListener {
if (it is ResolvableApiException) {
try {
//GPS is OFF
Toast.makeText(this, "Mohon aktifkan GPS anda",
Toast.LENGTH_LONG).show()
} catch (sendEx: IntentSender.SendIntentException) {
// Ignore the error.
}
}
}
and dont forget to check user's permission
Upvotes: 0
Reputation: 1018
The location object may be null in the following situations:
You should requestLocationUpdates when lastLocation == null
Upvotes: 2