¿Cómo mostrar el diálogo de habilitar ubicación como los mapas de Google?

Utilizo la última versión de Google Play Services (7.0) y seguí los pasos indicados en su guía y habilité el cuadro de diálogo de ubicación como se muestra a continuación, que tiene un botón “nunca”. Mi aplicación necesita obligatoriamente la ubicación, por lo que no quiero mostrarla nunca al usuario, porque una vez que el usuario hace clic en “nunca”, no puedo obtener la ubicación o solicitar la ubicación nuevamente.

¿Dónde, como Google Maps tiene solo sí y ningún botón sin botón nunca, alguna idea de cómo lograr lo mismo?

La imagen de mi aplicación enter image description here

Imagen de Google Map enter image description here

LocationSettingsRequest.Builder tiene un método setAlwaysShow(boolean show) . Si bien el documento indica que actualmente no está haciendo nada (actualizado el 2015-07-05: la documentación actualizada de Google ha eliminado esta redacción), estableciendo builder.setAlwaysShow(true); habilitará el comportamiento de Google Maps: enter image description here

Aquí está el código que lo hizo funcionar:

  if (googleApiClient == null) { googleApiClient = new GoogleApiClient.Builder(getActivity()) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this).build(); googleApiClient.connect(); LocationRequest locationRequest = LocationRequest.create(); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); locationRequest.setInterval(30 * 1000); locationRequest.setFastestInterval(5 * 1000); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() .addLocationRequest(locationRequest); //************************** builder.setAlwaysShow(true); //this is the key ingredient //************************** PendingResult result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build()); result.setResultCallback(new ResultCallback() { @Override public void onResult(LocationSettingsResult result) { final Status status = result.getStatus(); final LocationSettingsStates state = result.getLocationSettingsStates(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: // All location settings are satisfied. The client can initialize location // requests here. break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: // Location settings are not satisfied. But could be fixed by showing the user // a dialog. try { // Show the dialog by calling startResolutionForResult(), // and check the result in onActivityResult(). status.startResolutionForResult( getActivity(), 1000); } catch (IntentSender.SendIntentException e) { // Ignore the 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; } } }); } 

De la documentación de Android

Me gustaría agregar algunos cambios a la respuesta de Kai para aquellos que están buscando manejar botones Sí / No.

Declara esta constante en tu actividad

 protected static final int REQUEST_CHECK_SETTINGS = 0x1; 

llama a settingsrequest() en tu onStart ()

 public void settingsrequest() { LocationRequest locationRequest = LocationRequest.create(); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); locationRequest.setInterval(30 * 1000); locationRequest.setFastestInterval(5 * 1000); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() .addLocationRequest(locationRequest); builder.setAlwaysShow(true); //this is the key ingredient PendingResult result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build()); result.setResultCallback(new ResultCallback() { @Override public void onResult(LocationSettingsResult result) { final Status status = result.getStatus(); final LocationSettingsStates state = result.getLocationSettingsStates(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: // All location settings are satisfied. The client can initialize location // requests here. break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: // Location settings are not satisfied. But could be fixed by showing the user // a dialog. try { // Show the dialog by calling startResolutionForResult(), // and check the result in onActivityResult(). status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException e) { // Ignore the 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; } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { // Check for the integer request code originally supplied to startResolutionForResult(). case REQUEST_CHECK_SETTINGS: switch (resultCode) { case Activity.RESULT_OK: startLocationUpdates(); break; case Activity.RESULT_CANCELED: settingsrequest();//keep asking if imp or do whatever break; } break; } } 

¿Es similar a google maps? Código fuente

https://drive.google.com/open?id=0BzBKpZ4nzNzUOXM2eEhHM3hOZk0

Agregar dependencia en el archivo build.gradle

comstackr ‘com.google.android.gms: play-services: 8.3.0’

 this or that 

comstackr ‘com.google.android.gms: play-services-location: 10.0.1’ enter image description here

 package com.keshav.volleypostexample; import android.content.Context; import android.content.IntentSender; import android.location.LocationManager; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResult; import com.google.android.gms.location.LocationSettingsStatusCodes; import java.util.List; public class LocationOnOff_Similar_To_Google_Maps extends AppCompatActivity { protected static final String TAG = "LocationOnOff"; private GoogleApiClient googleApiClient; final static int REQUEST_LOCATION = 199; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setFinishOnTouchOutside(true); // Todo Location Already on ... start final LocationManager manager = (LocationManager) LocationOnOff_Similar_To_Google_Maps.this.getSystemService(Context.LOCATION_SERVICE); if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(LocationOnOff_Similar_To_Google_Maps.this)) { Toast.makeText(LocationOnOff_Similar_To_Google_Maps.this,"Gps already enabled",Toast.LENGTH_SHORT).show(); finish(); } // Todo Location Already on ... end if(!hasGPSDevice(LocationOnOff_Similar_To_Google_Maps.this)){ Toast.makeText(LocationOnOff_Similar_To_Google_Maps.this,"Gps not Supported",Toast.LENGTH_SHORT).show(); } if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(LocationOnOff_Similar_To_Google_Maps.this)) { Log.e("keshav","Gps already enabled"); Toast.makeText(LocationOnOff_Similar_To_Google_Maps.this,"Gps not enabled",Toast.LENGTH_SHORT).show(); enableLoc(); }else{ Log.e("keshav","Gps already enabled"); Toast.makeText(LocationOnOff_Similar_To_Google_Maps.this,"Gps already enabled",Toast.LENGTH_SHORT).show(); } } private boolean hasGPSDevice(Context context) { final LocationManager mgr = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); if (mgr == null) return false; final List providers = mgr.getAllProviders(); if (providers == null) return false; return providers.contains(LocationManager.GPS_PROVIDER); } private void enableLoc() { if (googleApiClient == null) { googleApiClient = new GoogleApiClient.Builder(LocationOnOff_Similar_To_Google_Maps.this) .addApi(LocationServices.API) .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() { @Override public void onConnected(Bundle bundle) { } @Override public void onConnectionSuspended(int i) { googleApiClient.connect(); } }) .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() { @Override public void onConnectionFailed(ConnectionResult connectionResult) { Log.d("Location error","Location error " + connectionResult.getErrorCode()); } }).build(); googleApiClient.connect(); LocationRequest locationRequest = LocationRequest.create(); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); locationRequest.setInterval(30 * 1000); locationRequest.setFastestInterval(5 * 1000); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() .addLocationRequest(locationRequest); builder.setAlwaysShow(true); PendingResult result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build()); result.setResultCallback(new ResultCallback() { @Override public void onResult(LocationSettingsResult result) { final Status status = result.getStatus(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: try { // Show the dialog by calling startResolutionForResult(), // and check the result in onActivityResult(). status.startResolutionForResult(LocationOnOff_Similar_To_Google_Maps.this, REQUEST_LOCATION); finish(); } catch (IntentSender.SendIntentException e) { // Ignore the error. } break; } } }); } } } 

Dependencia

 compile 'com.google.android.gms:play-services-location:10.0.1' 

Código

 import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.IntentSender; import android.location.LocationManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResult; import com.google.android.gms.location.LocationSettingsStates; import com.google.android.gms.location.LocationSettingsStatusCodes; public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { public static final int REQUEST_LOCATION=001; GoogleApiClient googleApiClient; LocationManager locationManager; LocationRequest locationRequest; LocationSettingsRequest.Builder locationSettingsRequest; Context context; PendingResult pendingResult; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); context = this; locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { Toast.makeText(this, "Gps is Enabled", Toast.LENGTH_SHORT).show(); } else { mEnableGps(); } } public void mEnableGps() { googleApiClient = new GoogleApiClient.Builder(context) .addApi(LocationServices.API).addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); googleApiClient.connect(); mLocationSetting(); } public void mLocationSetting() { locationRequest = LocationRequest.create(); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); locationRequest.setInterval(1 * 1000); locationRequest.setFastestInterval(1 * 1000); locationSettingsRequest = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest); mResult(); } public void mResult() { pendingResult = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, locationSettingsRequest.build()); pendingResult.setResultCallback(new ResultCallback() { @Override public void onResult(@NonNull LocationSettingsResult locationSettingsResult) { Status status = locationSettingsResult.getStatus(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: // All location settings are satisfied. The client can initialize location // requests here. break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: try { status.startResolutionForResult(MainActivity.this, REQUEST_LOCATION); } catch (IntentSender.SendIntentException e) { } 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; } } }); } //callback method @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { final LocationSettingsStates states = LocationSettingsStates.fromIntent(data); switch (requestCode) { case REQUEST_LOCATION: switch (resultCode) { case Activity.RESULT_OK: // All required changes were successfully made Toast.makeText(context, "Gps enabled", Toast.LENGTH_SHORT).show(); break; case Activity.RESULT_CANCELED: // The user was asked to change settings, but chose not to Toast.makeText(context, "Gps Canceled", Toast.LENGTH_SHORT).show(); break; default: break; } break; } } @Override public void onConnected(@Nullable Bundle bundle) { } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } } 

Ola Cabs está utilizando la recientemente liberada API de configuración para lograr esta funcionalidad. Según la nueva API, no es necesario que el usuario acceda a la página de configuración para habilitar los servicios de ubicación y obtener una integración perfecta para la misma. Por favor, lea a continuación para más detalles:

https://developers.google.com/android/reference/com/google/android/gms/location/SettingsApi

También puede agregar varias LocationRequests for Builder para lograr el diálogo “Utilizar GPS, Wi-Fi y redes móviles para la ubicación”, en lugar de “Usar el GPS para la ubicación”

 LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() .addLocationRequest(createLocationRequest(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)) .addLocationRequest(createLocationRequest(LocationRequest.PRIORITY_HIGH_ACCURACY)) .setAlwaysShow(true); PendingResult result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build()); 

LocationServices.SettingsApi está en desuso ahora, entonces usamos SettingsClient

  LocationRequest mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(10); mLocationRequest.setSmallestDisplacement(10); mLocationRequest.setFastestInterval(10); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); builder.addLocationRequest(mLocationRequest); 

Luego verifica si la configuración de ubicación actual está satisfecha. Cree la tarea LocationSettingsResponse:

  Task task=LocationServices.getSettingsClient(this).checkLocationSettings(builder.build()); 

A continuación, agregue Listener

 task.addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(Task 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( HomeActivity.this, 101); } 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; } } } }); 

Agregado en ActivityResult

 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { final LocationSettingsStates states = LocationSettingsStates.fromIntent(data); switch (requestCode) { case 101: switch (resultCode) { case Activity.RESULT_OK: // All required changes were successfully made Toast.makeText(HomeActivity.this,states.isLocationPresent()+"",Toast.LENGTH_SHORT).show(); break; case Activity.RESULT_CANCELED: // The user was asked to change settings, but chose not to Toast.makeText(HomeActivity.this,"Canceled",Toast.LENGTH_SHORT).show(); break; default: break; } break; } } 

Consulte el enlace ConfiguracionesCliente