Pregunta

Actualmente estoy escribiendo una aplicación en Android que funciona con el GPS. En este momento puedo determinar si el GPS está habilitado. Mi problema es que quiero habilitar el GPS al iniciar la aplicación si está deshabilitado. ¿Cómo puedo hacer esto programáticamente?

¿Fue útil?

Solución

No puedes, comenzando con Android 1.5. Lo máximo que puede hacer es abrir la actividad para permitir que el usuario la active o desactive. Use la acción contenida en android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS para elaborar un Intento para abrir esta actividad.

Otros consejos

if(!LocationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER ))
{
    Intent myIntent = new Intent( Settings.ACTION_SECURITY_SETTINGS );
    startActivity(myIntent);
}

Este código de método puede ser de ayuda para usted

private void turnGPSOnOff(){
  String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
  if(!provider.contains("gps")){
    final Intent poke = new Intent();
    poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
    poke.setData(Uri.parse("3")); 
    sendBroadcast(poke);
    //Toast.makeText(this, "Your GPS is Enabled",Toast.LENGTH_SHORT).show();
  }
}

Puede usar lo siguiente:

try {
  Settings.Secure.setLocationProviderEnabled(getContentResolver(), LocationManager.GPS_PROVIDER, true);
} catch (Exception e) {
  logger.log(Log.ERROR, e, e.getMessage());
}

pero solo funcionará si tiene un nivel de protección de firma del sistema. Por lo tanto, debe cocinar su propia imagen para usarla realmente: /

Primero verifica si el servicio de ubicación ya está activado o no ??

Verificar el servicio de ubicación está habilitado o no

public boolean isLocationServiceEnabled(){
    LocationManager locationManager = null;
    boolean gps_enabled= false,network_enabled = false;

    if(locationManager ==null)
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    try{
        gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }catch(Exception ex){
        //do nothing...
    }

    try{
        network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    }catch(Exception ex){
        //do nothing...
    }

    return gps_enabled || network_enabled;

}

Luego, finalmente, para abrir si el servicio de ubicación está desactivado anteriormente

  if (isLocationServiceEnabled())) {
          //DO what you need...
     } else {
          AlertDialog.Builder builder = new AlertDialog.Builder(this);
          builder.setMessage("Seems Like location service is off,   Enable this to show map")
      .setPositiveButton("YES", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
                             Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                    startActivity(intent);
                                }
                            }).setNegativeButton("NO THANKS", null).create().show();
                }

Debe usar la Configuración de ubicación Diálogo en Play Services que solicita al usuario que habilite los servicios de ubicación (si es necesario) con solo un clic.

si su pregunta está en el nivel de usuario de Android, estas propiedades se encuentran en: "Settings -> Location -> Use wireless networks" -> "Settings -> Location -> Use GPS satellites".

Pero en el desarrollador puede usar la clase "android.provider.Settings.Secure" con los permisos apropiados.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top