ubicación ubicaciones ubicacion quitar icono historial google desde desactivar como chrome actual activar android service location

android - ubicaciones - ubicacion actual



¿Cómo verificar si los Servicios de localización están habilitados? (15)

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

Estoy desarrollando una aplicación en el sistema operativo Android. No sé cómo verificar si los Servicios de localización están habilitados o no.

Necesito un método que devuelva "verdadero" si están habilitados y "falso" si no (así que en el último caso puedo mostrar un diálogo para habilitarlos).


Esta cláusula if revisa 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 }


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; }


Para obtener la ubicación geográfica actual en los mapas de Google 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(); } }


Para verificar si hay un proveedor de red, solo tiene que cambiar la cadena pasada a isProviderEnabled a LocationManager.NETWORK_PROVIDER si verifica los valores devueltos para el proveedor de GPS y el proveedor de NETwork, ambos falsos significan que no hay servicios de ubicación.


Puede solicitar las actualizaciones de ubicación y mostrar el cuadro de diálogo juntos, como también las cuentas de GoogleMaps. 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 .


Puede usar el siguiente código para verificar si el proveedor gps y los proveedores de la 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(); }


Puede usar este código para dirigir a los usuarios a Configuración, donde pueden habilitar el 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; }


Sí, puedes consultar a continuación 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" />


Si no hay ningún proveedor habilitado, "pasivo" es el mejor proveedor devuelto. Ver https://.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)); }


Trabajando con la respuesta anterior, en la API 23 necesita agregar comprobaciones de permisos "peligrosas" y verificar el sistema mismo:

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); }


Utilizo dicho método para NETWORK_PROVIDER pero puede agregarlo y para GPS .

LocationManager locationManager;

En onCreate puse

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 el método de comprobación

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


Yo uso este código para verificar:

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); } }


utilizo el primer código begin create method isLocationEnabled

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

y compruebo la condición si ture Abre el mapa y da falso intento ACTION_LOCATION_SOURCE_SETTINGS

if (isLocationEnabled()) { SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); locationClient = getFusedLocationProviderClient(this); locationClient.getLastLocation() .addOnSuccessListener(new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { // GPS location can be null if GPS is switched off if (location != null) { onLocationChanged(location); Log.e("location", String.valueOf(location.getLongitude())); } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.e("MapDemoActivity", e.toString()); e.printStackTrace(); } }); startLocationUpdates(); } else { new AlertDialog.Builder(this) .setTitle("Please activate location") .setMessage("Click ok to goto settings else exit.") .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); } }) .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { System.exit(0); } }) .show(); }


private boolean isGpsEnabled() { LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE); return service.isProviderEnabled(LocationManager.GPS_PROVIDER)&&service.isProviderEnabled(LocationManager.NETWORK_PROVIDER); }