Issue
i have an issue. My app has required location service, so i run the code above to show a dialog to the user and if the user clicks "OK" I activate the location and save the event.
Code to check and show the dialog if the location is deactivated:
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private void askForLocationChange() {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
SettingsClient client = LocationServices.getSettingsClient(this);
Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
task.addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
getLastKnownLocation(); //Works fine
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
//Shows the dialog
if (e instanceof ResolvableApiException) {
try {
ResolvableApiException resolvable = (ResolvableApiException) e;
resolvable.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException ignored) {
}
}
}
});
}
@EDIT I changed a little and it works pretty well... if location is activated previously...
I'm using a listener and get the location only in the onLocationChanged function... but if the location is deactivated, after active (above code), the location has a delay very large, what google uses on the google maps? because if u enter google maps with the location off, and active it, the location is show on the map after a few seconds.
Solution
I have used the same listener, if the user activates the location i create the listener and remove it before i get the location on the onLocationChange method, because sometimes it takes around 10 seconds to get the user location.
@Override
public void onLocationChanged(@NonNull Location location) {
//Save Event
stopUsingGPS();
}
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
And after i get the location i remove the listener.
Answered By - E. Greeff
Answer Checked By - Robin (JavaFixing Admin)