¿Cómo puedo saber si el GPS de un dispositivo Android está habilitado?

Respuestas:

456

La mejor manera parece ser la siguiente:

 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(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                   startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    dialog.cancel();
               }
           });
    final AlertDialog alert = builder.create();
    alert.show();
}
Marcus
fuente
1
Principalmente se trata de activar una intención de ver la configuración del GPS, ver github.com/marcust/HHPT/blob/master/src/org/thiesen/hhpt/ui/… para más detalles.
Marcus
3
Bonito fragmento de código. Eliminé @SuppressWarnings y no recibo ninguna advertencia ... ¿tal vez son innecesarias?
abarcan el
30
Aconsejaría declarar alerttoda la actividad para que pueda descartarla en onDestroy para evitar una pérdida de memoria ( if(alert != null) { alert.dismiss(); })
Cameron
¿Y qué pasa si estoy ahorrando batería? ¿Funcionará?
Prakhar Mohan Srivastava
3
@PrakharMohanSrivastava si la configuración de ubicación está en Ahorro de energía, esto será falso, sin embargo, LocationManager.NETWORK_PROVIDERserá verdadero
Tim
129

En Android, podemos verificar fácilmente si el GPS está habilitado en el dispositivo o no usando LocationManager.

Aquí hay un programa simple para verificar.

GPS habilitado o no: - Agregue la siguiente línea de permiso de usuario en AndroidManifest.xml para acceder a la ubicación

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

Su archivo de clase de Java debe ser

public class ExampleApp extends Activity {
    /** Called when the activity is first created. */
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
        }else{
            showGPSDisabledAlertToUser();
        }
    }

    private void showGPSDisabledAlertToUser(){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
        .setCancelable(false)
        .setPositiveButton("Goto Settings Page To Enable GPS",
                new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                Intent callGPSSettingIntent = new Intent(
                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(callGPSSettingIntent);
            }
        });
        alertDialogBuilder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                dialog.cancel();
            }
        });
        AlertDialog alert = alertDialogBuilder.create();
        alert.show();
    }
}

La salida se verá como

ingrese la descripción de la imagen aquí

ingrese la descripción de la imagen aquí

berilio
fuente
1
No pasa nada cuando pruebo tu función. Sin embargo, no obtuve errores cuando lo pruebo.
Airikr
¡Lo tengo funcionando! :) Muchas gracias pero no puedo votar hasta que haya editado su respuesta: /
Airikr
3
no hay problema @Erik Edgren obtienes una solución, así que estoy feliz ¡DISFRUTA ...!
@ user647826: ¡Excelente! Funciona bien Me salvaste la noche
Addi
1
Un consejo: declara alerttoda la actividad para que puedas descartarla onDestroy()para evitar una pérdida de memoria ( if(alert != null) { alert.dismiss(); })
naXa
38

sí, la configuración del GPS ya no se puede cambiar programáticamente, ya que son configuraciones de privacidad y tenemos que verificar si están activadas o no desde el programa y manejarlas si no están activadas. puede notificar al usuario que el GPS está apagado y usar algo como esto para mostrar la pantalla de configuración al usuario si lo desea.

Verifique si hay proveedores de ubicación disponibles

    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if(provider != null){
        Log.v(TAG, " Location providers: "+provider);
        //Start searching for location and update the location text when update available
        startFetchingLocation();
    }else{
        // Notify users and show settings if they want to enable GPS
    }

Si el usuario desea habilitar el GPS, puede mostrar la pantalla de configuración de esta manera.

Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, REQUEST_CODE);

Y en su onActivityResult puede ver si el usuario lo ha habilitado o no

    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if(requestCode == REQUEST_CODE && resultCode == 0){
            String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            if(provider != null){
                Log.v(TAG, " Location providers: "+provider);
                //Start searching for location and update the location text when update available. 
// Do whatever you want
                startFetchingLocation();
            }else{
                //Users did not switch on the GPS
            }
        }
    }

Esa es una forma de hacerlo y espero que ayude. Avísame si estoy haciendo algo mal.

achie
fuente
2
hola, tengo un problema similar ... ¿puedes explicar brevemente qué es el "REQUEST_CODE" y para qué sirve?
Poeschlorn
2
@poeschlorn Anna publicó el enlace que se detalla a continuación. En términos simples, RequestCode le permite usar startActivityForResultcon múltiples intentos. Cuando los intentos regresan a su actividad, usted verifica el RequestCode para ver qué intento regresa y responde en consecuencia.
Farray
2
El providerpuede ser una cadena vacía. Tuve que cambiar el cheque a(provider != null && !provider.isEmpty())
Pawan
Como el proveedor puede ser "", considere usar int mode = Settings.Secure.getInt (getContentResolver (), Settings.Secure.LOCATION_MODE); Si el modo = 0 GPS está apagado
Levon Petrosyan
31

Aquí están los pasos:

Paso 1: crear servicios que se ejecutan en segundo plano.

Paso 2: También necesita el siguiente permiso en el archivo de manifiesto:

android.permission.ACCESS_FINE_LOCATION

Paso 3: escribe el código:

 final LocationManager manager = (LocationManager)context.getSystemService    (Context.LOCATION_SERVICE );

if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) )
  Toast.makeText(context, "GPS is disabled!", Toast.LENGTH_LONG).show(); 
else
  Toast.makeText(context, "GPS is enabled!", Toast.LENGTH_LONG).show();

Paso 4: O simplemente puedes verificar usando:

LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);

Paso 5: Ejecute sus servicios continuamente para monitorear la conexión.

Rakesh
fuente
55
Indica que el GPS está habilitado incluso cuando está apagado.
Ivan V
15

Sí, puedes verificar a continuación el código:

public boolean isGPSEnabled (Context mContext){
    LocationManager locationManager = (LocationManager)
                mContext.getSystemService(Context.LOCATION_SERVICE);
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
Arun kumar
fuente
9

Este método usará el servicio LocationManager .

Enlace fuente

//Check GPS Status true/false
public static boolean checkGPSStatus(Context context){
    LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE );
    boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    return statusOfGPS;
};
Code Spy
fuente
6

Se usará el GPS si el usuario ha permitido que se use en su configuración.

Ya no puede activarlo explícitamente, pero no tiene que hacerlo: es una configuración de privacidad realmente, por lo que no desea modificarlo. Si el usuario está de acuerdo con que las aplicaciones obtengan coordenadas precisas, estará activado. Luego, la API del administrador de ubicación usará GPS si puede.

Si su aplicación realmente no es útil sin GPS, y está desactivada, puede abrir la aplicación de configuración en la pantalla derecha con una intención para que el usuario pueda habilitarla.


fuente
6

Este código comprueba el estado del GPS

final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
    buildAlertMessageNoGps();
}

``

kashifahmad
fuente
3

En sus controladores de LocationListenerimplementación onProviderEnabledy onProviderDisabledeventos. Cuando llame requestLocationUpdates(...), si el GPS está deshabilitado en el teléfono, onProviderDisabledse le llamará; si el usuario habilita el GPS, onProviderEnabledse le llamará.

Ahmad Pourbafrani
fuente
2
In Kotlin: - How to check GPS is enable or not

 val manager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            checkGPSEnable()

        } 


 private fun checkGPSEnable() {
        val dialogBuilder = AlertDialog.Builder(this)
        dialogBuilder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
                .setCancelable(false)
                .setPositiveButton("Yes", DialogInterface.OnClickListener { dialog, id
                    ->
                    startActivity(Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS))
                })
                .setNegativeButton("No", DialogInterface.OnClickListener { dialog, id ->
                    dialog.cancel()
                })
        val alert = dialogBuilder.create()
        alert.show()
    }
safal bhatia
fuente