2010-08-12 11 views

Respuesta

19

Si desea capturar la ubicación con un botón pulsado, así es como lo haría. Si el usuario no tiene habilitado un servicio de ubicación, esto lo enviará al menú de configuración para habilitarlo.

En primer lugar, se debe agregar el permiso "android.permission.ACCESS_COARSE_LOCATION" a su manifiesto. Si necesita GPS (ubicación de red no es lo suficientemente sensible), agregar el permiso "android.permission.ACCESS_FINE_LOCATION" en su lugar, y cambiar el "Criteria.ACCURACY_COARSE" a "Criteria.ACCURACY_FINE"

Button gpsButton = (Button)this.findViewById(R.id.buttonGPSLocation); 
gpsButton.setOnClickListener(new OnClickListener() { 

    @Override 
    public void onClick(View v) { 
     // Start loction service 
     LocationManager locationManager = (LocationManager)[OUTERCLASS].this.getSystemService(Context.LOCATION_SERVICE); 

     Criteria locationCritera = new Criteria(); 
     locationCritera.setAccuracy(Criteria.ACCURACY_COARSE); 
     locationCritera.setAltitudeRequired(false); 
     locationCritera.setBearingRequired(false); 
     locationCritera.setCostAllowed(true); 
     locationCritera.setPowerRequirement(Criteria.NO_REQUIREMENT); 

     String providerName = locationManager.getBestProvider(locationCritera, true); 

     if (providerName != null && locationManager.isProviderEnabled(providerName)) { 
      // Provider is enabled 
      locationManager.requestLocationUpdates(providerName, 20000, 100, [OUTERCLASS].this.locationListener); 
     } else { 
      // Provider not enabled, prompt user to enable it 
      Toast.makeText([OUTERCLASS].this, R.string.please_turn_on_gps, Toast.LENGTH_LONG).show(); 
      Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
      [OUTERCLASS].this.startActivity(myIntent); 
     } 
    } 
}); 

Mi clase externa tiene este oyente configurado

private final LocationListener locationListener = new LocationListener() { 

    @Override 
    public void onLocationChanged(Location location) { 
     [OUTERCLASS].this.gpsLocationReceived(location); 
    } 

    @Override 
    public void onProviderDisabled(String provider) {} 

    @Override 
    public void onProviderEnabled(String provider) {} 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) {} 

}; 

Luego, cuando quiera dejar de escuchar, llame a esto. Al menos deberías hacer esta llamada durante el método onStop de tu actividad.

LocationManager locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE); 
locationManager.removeUpdates(this.locationListener); 
+2

El segundo parámetro en getBestProvider (locationCritera, verdaderos) comprueba que los proveedores sean habilitado, por lo tanto, en teoría, no necesita verificar si está habilitado nuevamente. – Eduardo

0

para pedir al usuario a los servicios de localización que debe utilizar el nuevo LocationRequest incluido en servicios de Google Play, podemos encontrar la guía completa en LocationRequest

2

Después de pasar por un montón de respuestas sobre desbordamiento de pila, Encontré que este método funciona perfectamente bien y ni siquiera requiere una gran cantidad de código.
Declare int GPSoff = 0 como una variable global.
Ahora siempre que se necesite para comprobar el estado actual del GPS y redirigir al usuario activar el GPS, utiliza esta:

try { 
       GPSoff = Settings.Secure.getInt(getContentResolver(),Settings.Secure.LOCATION_MODE); 
      } catch (Settings.SettingNotFoundException e) { 
       e.printStackTrace(); 
      } 
      if (GPSoff == 0) { 
       showMessageOKCancel("You need to turn Location On", 
         new DialogInterface.OnClickListener() { 
          @Override 
          public void onClick(DialogInterface dialog, int which) { 
           Intent onGPS = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
           startActivity(onGPS); 
          } 
         }); 
      } 
+0

¿Qué es getContentResolver(), showMessageOKCancel & startActivity? Todos están sin resolver – hfz

Cuestiones relacionadas