este problema se puede resolver de diferentes formas, pero te enseñamos la resolución más completa para nosotros.
Solución:
Utilice el siguiente código para comprobarlo. Si está deshabilitado, se generará un cuadro de diálogo
public void statusCheck()
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER))
buildAlertMessageNoGps();
private void buildAlertMessageNoGps()
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
public void onClick(final DialogInterface dialog, final int id)
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
)
.setNegativeButton("No", new DialogInterface.OnClickListener()
public void onClick(final DialogInterface dialog, final int id)
dialog.cancel();
);
final AlertDialog alert = builder.create();
alert.show();
Puede probar estos métodos a continuación:
Para verificar si el GPS y el proveedor de red están habilitados:
public boolean canGetLocation()
boolean result = true;
LocationManager lm;
boolean gpsEnabled = false;
boolean networkEnabled = false;
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// exceptions will be thrown if provider is not permitted.
try
gpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
catch (Exception ex)
try
networkEnabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
catch (Exception ex)
return gpsEnabled && networkEnabled;
Diálogo de alerta si el código anterior regresa false:
public void showSettingsAlert()
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
// Setting Dialog Title
alertDialog.setTitle("Error!");
// Setting Dialog Message
alertDialog.setMessage("Please ");
// On pressing Settings button
alertDialog.setPositiveButton(
getResources().getString(R.string.button_ok),
new DialogInterface.OnClickListener()
public void onClick(DialogInterface dialog, int which)
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
);
alertDialog.show();
Cómo utilizar los dos métodos anteriores:
if (canGetLocation())
//DO SOMETHING USEFUL HERE. ALL GPS PROVIDERS ARE CURRENTLY ENABLED
else
//SHOW OUR SETTINGS ALERT, AND LET THE USE TURN ON ALL THE GPS PROVIDERS
showSettingsAlert();
A continuación, se muestra una forma sencilla de habilitar ubicaciones mediante programación, como la aplicación Mapas:
protected void enableLocationSettings()
LocationRequest locationRequest = LocationRequest.create()
.setInterval(LOCATION_UPDATE_INTERVAL)
.setFastestInterval(LOCATION_UPDATE_FASTEST_INTERVAL)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
LocationServices
.getSettingsClient(this)
.checkLocationSettings(builder.build())
.addOnSuccessListener(this, (LocationSettingsResponse response) ->
// startUpdatingLocation(...);
)
.addOnFailureListener(this, ex ->
if (ex instanceof ResolvableApiException)
// Location settings are NOT satisfied, but this can be fixed by showing the user a dialog.
try
// Show the dialog by calling startResolutionForResult(), and check the result in onActivityResult().
ResolvableApiException resolvable = (ResolvableApiException) ex;
resolvable.startResolutionForResult(TrackingListActivity.this, REQUEST_CODE_CHECK_SETTINGS);
catch (IntentSender.SendIntentException sendEx)
// Ignore the error.
);
Y onActivityResult:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
if (REQUEST_CODE_CHECK_SETTINGS == requestCode)
if(Activity.RESULT_OK == resultCode)
//user clicked OK, you can startUpdatingLocation(...);
else
//user clicked cancel: informUserImportanceOfLocationAndPresentRequestAgain();
Puede ver la documentación aquí: https://developer.android.com/training/location/change-location-settings
Sección de Reseñas y Valoraciones
Si tienes alguna suspicacia y forma de medrar nuestro escrito te recordamos realizar un paráfrasis y con deseo lo interpretaremos.