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