¿Cómo comprobar si los servicios de ubicación están habilitados?

Estoy desarrollando una aplicación en Android OS. No sé cómo comprobar si los Servicios de ubicación están habilitados o no.

Necesito un método que devuelva "true" si están habilitados y "false" si no (por lo que en el último caso puedo mostrar un diálogo para habilitarlos).

Puede utilizar el siguiente código para comprobar si el proveedor de gps y los proveedores de red están habilitados o no.

LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); boolean gps_enabled = false; boolean network_enabled = false; try { gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); } catch(Exception ex) {} try { network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch(Exception ex) {} if(!gps_enabled && !network_enabled) { // notify user AlertDialog.Builder dialog = new AlertDialog.Builder(context); dialog.setMessage(context.getResources().getString(R.string.gps_network_not_enabled)); dialog.setPositiveButton(context.getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface paramDialogInterface, int paramInt) { // TODO Auto-generated method stub Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS); context.startActivity(myIntent); //get gps } }); dialog.setNegativeButton(context.getString(R.string.Cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface paramDialogInterface, int paramInt) { // TODO Auto-generated method stub } }); dialog.show(); } 

Utilizo este código para comprobar:

 public static boolean isLocationEnabled(Context context) { int locationMode = 0; String locationProviders; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){ try { locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE); } catch (SettingNotFoundException e) { e.printStackTrace(); return false; } return locationMode != Settings.Secure.LOCATION_MODE_OFF; }else{ locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); return !TextUtils.isEmpty(locationProviders); } } 

Puede utilizar este código para dirigir a los usuarios a Configuración, donde pueden activar GPS:

  locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); if( !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.gps_not_found_title); // GPS not found builder.setMessage(R.string.gps_not_found_message); // Want to enable? builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int i) { owner.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); } }); builder.setNegativeButton(R.string.no, null); builder.create().show(); return; } 

Trabajando de la respuesta anterior, en la API 23 necesitas agregar controles de permisos "peligrosos" así como comprobar el propio sistema:

 public static boolean isLocationServicesAvailable(Context context) { int locationMode = 0; String locationProviders; boolean isAvailable = false; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){ try { locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE); } catch (Settings.SettingNotFoundException e) { e.printStackTrace(); } isAvailable = (locationMode != Settings.Secure.LOCATION_MODE_OFF); } else { locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); isAvailable = !TextUtils.isEmpty(locationProviders); } boolean coarsePermissionCheck = (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED); boolean finePermissionCheck = (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED); return isAvailable && (coarsePermissionCheck || finePermissionCheck); } 

Si no se habilita ningún proveedor, "pasivo" es el mejor proveedor devuelto. Consulte https://stackoverflow.com/a/4519414/621690

  public boolean isLocationServiceEnabled() { LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); String provider = lm.getBestProvider(new Criteria(), true); return (StringUtils.isNotBlank(provider) && !LocationManager.PASSIVE_PROVIDER.equals(provider)); } 

Esta cláusula if comprueba fácilmente si los servicios de localización están disponibles en mi opinión:

 LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { //All location services are disabled } 

Como indicó Peter McClennan, Google tiene una API que funciona muy bien con el nuevo proveedor de ubicación fusionada. Un ejemplo completamente trabajado está en Google Sample Code en Github No es necesario codificar un diálogo de usuario para pedirles que cambien la configuración, ya que se realiza automáticamente con la API.

Si usted puede comprobar abajo es el código:

 public boolean isGPSEnabled(Context mContext) { LocationManager lm = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); return lm.isProviderEnabled(LocationManager.GPS_PROVIDER); } 

Con el permiso en el archivo de manifiesto:

 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

Para obtener la ubicación actual de Geo en google maps android, debe activar la opción de ubicación del dispositivo. Para comprobar si la ubicación está activada o no, puede llamar a este método desde su método onCreate() .

 private void checkGPSStatus() { LocationManager locationManager = null; boolean gps_enabled = false; boolean network_enabled = false; if ( locationManager == null ) { locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); } try { gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); } catch (Exception ex){} try { network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch (Exception ex){} if ( !gps_enabled && !network_enabled ){ AlertDialog.Builder dialog = new AlertDialog.Builder(MyActivity.this); dialog.setMessage("GPS not enabled"); dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //this will navigate user to the device location settings screen Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); } }); AlertDialog alert = dialog.create(); alert.show(); } } 

Yo uso de esta manera para NETWORK_PROVIDER pero puede agregar y para GPS .

 LocationManager locationManager; 

En onCreate pongo

  isLocationEnabled(); if(!isLocationEnabled()) { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle(R.string.network_not_enabled) .setMessage(R.string.open_location_settings) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } 

Y método de verificación

 protected boolean isLocationEnabled(){ String le = Context.LOCATION_SERVICE; locationManager = (LocationManager) getSystemService(le); if(!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){ return false; } else { return true; } } 

Este es un método muy útil que devuelve " true " si los Location services están habilitados:

 public static boolean locationServicesEnabled(Context context) { LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); boolean gps_enabled = false; boolean net_enabled = false; try { gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); } catch (Exception ex) { Log.e(TAG,"Exception gps_enabled"); } try { net_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch (Exception ex) { Log.e(TAG,"Exception network_enabled"); } return gps_enabled || net_enabled; } 

Puede solicitar las actualizaciones de la ubicación y mostrar el diálogo juntos, como Googlemas también. Aquí está el código:

 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<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build()); result.setResultCallback(new ResultCallback<LocationSettingsResult>() { @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 ignored) {} 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; } } }); } 

Si necesita más información, consulte la clase LocationRequest .

Para comprobar el proveedor de la red sólo tiene que cambiar la cadena pasada a isProviderEnabled a LocationManager.NETWORK_PROVIDER si comprueba los valores devueltos tanto para el proveedor de GPS como para el proveedor de NETwork – ambos falsos significa que no hay servicios de ubicación

 private boolean isGpsEnabled() { LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE); return service.isProviderEnabled(LocationManager.GPS_PROVIDER)&&service.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } 
  • Mostrando una Snackbar desde dentro de un Servicio
  • Android Service se está ejecutando, pero no aparece en la configuración -> servicios en ejecución
  • Cómo obtener detalles del proceso de ejecución de fondo android
  • Mi BroadcastReceiver no está recibiendo la intención BOOT_COMPLETED después de mis botas N1
  • No se puede iniciar el servicio
  • Servicio de Android interactuando con múltiples actividades
  • ¿Cómo puedo reiniciar mi servicio de aplicaciones si el usuario lo detiene (mata) desde la configuración?
  • Cómo enviar el mensaje del servicio a la actividad
  • Utilizar IExtendedNetworkService para obtener respuesta de USSD en Android
  • La mejor manera de actualizar un widget de Android cada 20-30 segundos: Handler, Service or Alarm?
  • IntentService no se está llamando
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.