I am using the following methods to get the current location of the user. Problem is, if the user has the GPS already enabled, it might work. But if they don't have it enabled, I ask them to. After they enabled it, I still get "Unable to find Location". What am I doing wrong?
In checkLocation()
I check if the user has the GPS or Network provider enabled;
private void checkLocation() {
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER) && !lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
OnGPS();
} else {
getLocation(lm);
}
}
If it is not enabled, I ask them to enable it. Here is the method OnGPS()
private void OnGPS() {
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Enable GPS");
builder.setCancelable(true);
builder.setPositiveButton("Yes", (dialog, which) -> {
dialog.cancel();
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
});
builder.setNegativeButton("No", (dialog, which) -> dialog.cancel());
final AlertDialog alertDialog = builder.create();
alertDialog.show();
}
Below is my getLocation()
method
private void getLocation(LocationManager lm) {
if (ActivityCompat.checkSelfPermission(
context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
else
{
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
LocationServices.getSettingsClient(getActivity()).checkLocationSettings(builder.build());
Task<LocationSettingsResponse> result =
LocationServices.getSettingsClient(getActivity()).checkLocationSettings(builder.build());
result.addOnCompleteListener(task -> {
try {
LocationSettingsResponse response = task.getResult(ApiException.class);
// All location settings are satisfied. The client can initialize location
// requests here.
} catch (ApiException exception) {
switch (exception.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the
// user a dialog.
try {
// Cast to a resolvable exception.
ResolvableApiException resolvable = (ResolvableApiException) exception;
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
resolvable.startResolutionForResult(
getActivity(),
LocationRequest.PRIORITY_HIGH_ACCURACY);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
} catch (ClassCastException e) {
// Ignore, should be an impossible error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
Location locationGPS = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (locationGPS == null)
{
locationGPS = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (locationGPS != null) {
double lat = locationGPS.getLatitude();
double longt = locationGPS.getLongitude();
myGeofire.setLocation(currentUserID, new GeoLocation(lat, longt), (key, error) -> {
if (error == null) {
Log.e("GEOFIRE","Location saved on server successfully!");
} else {
Log.e("GEOFIRE","There was an error saving the location to GeoFire: " + error);
}
});
latitude = String.valueOf(lat);
longitude = String.valueOf(longt);
// Toast.makeText(FindFriendsActivity.this, "Lat: " + latitude + " Long: " + longitude, Toast.LENGTH_LONG).show();
HashMap<String, Object> profileMap = new HashMap<>();
profileMap.put("lat", latitude);
profileMap.put("longt", longitude);
rootRef.child("Users").child(currentUserID).updateChildren(profileMap)
.addOnCompleteListener(task ->
{
if (task.isSuccessful()) {
Log.d("Location:", latitude + longitude);
//Toast.makeText(FindFriendsActivity.this, "Location updated successfully!" , Toast.LENGTH_SHORT).show();
}
else{
String errorMSG = Objects.requireNonNull(task.getException()).toString();
Toast.makeText(context, "Error : " + errorMSG, Toast.LENGTH_SHORT).show();
}
});
}
else
{
Toast.makeText(context, "Unable to find location.", Toast.LENGTH_SHORT).show();
}
}
}
And lastly the methods onActivityResult()
and onLocationChanged()
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case LocationRequest.PRIORITY_HIGH_ACCURACY:
switch (resultCode) {
case Activity.RESULT_OK:
// All required changes were successfully made
Log.i("TAG", "onActivityResult: GPS Enabled by user");
checkLocation();
break;
case Activity.RESULT_CANCELED:
// The user was asked to change settings, but chose not to
Log.i("TAG", "onActivityResult: User rejected GPS request");
checkLocation();
break;
default:
break;
}
break;
}
}
@Override
public void onLocationChanged(@NonNull Location location) {
latitude = String.valueOf(location.getLatitude());
longitude = String.valueOf(location.getLongitude());
checkLocation();
}
I was able to solve it by adding the lines
if (locationGPS == null) {
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
locationGPS = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
}
in my getLocation()
method after the lines
Location locationGPS = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (locationGPS == null)
{
locationGPS = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}