I was playing a bit around the new location API from google (to get latitude and longitude values):
private void getLastLocation(){
FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
try {
mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Toast.makeText(getApplicationContext(), String.valueOf(latitude) + "/" + String.valueOf(longitude), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Cannot get location", Toast.LENGTH_LONG).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.d("LocationFetch", "Error trying to get last GPS location");
e.printStackTrace();
}
});
} catch (SecurityException e){
Log.d("LocationFetch", "Permission missing");
}
}
When I first tested this code, the location
was always returning null. However, after opening Instagram (which did a location update on my phone - the geo icon appeared briefly), the location
was returning my relevant longitude and latitude values.
How do I request a location update on my app using the new API to prevent location
from being null or retrieve very old locations? (getLastLocation()
is not enough, possibly LocationRequest
?)
It is worth noting that I do not want interval updates, I want for it to happen within an Android Service when invoked once.