Android requestLocationUpdates usando PendingIntent con BroadcastReceiver

¿Cómo uso

requestLocationUpdates(long minTime, float minDistance, Criteria criteria, PendingIntent intent) 

En BroadcastReciver para que pueda seguir recibiendo coordenadas GPS.

¿Tengo que crear una clase separada para el LocationListener?

El objetivo de mi proyecto es cuando recibo BOOT_COMPLETED para empezar a obtener GPS lats y longs periódicamente.

Código que intenté es:

 public class MobileViaNetReceiver extends BroadcastReceiver { LocationManager locmgr = null; String android_id; DbAdapter_GPS db; @Override public void onReceive(Context context, Intent intent) { if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) { startGPS(context); } else { Log.i("MobileViaNetReceiver", "Received unexpected intent " + intent.toString()); } } public void startGPS(Context context) { Toast.makeText(context, "Waiting for location...", Toast.LENGTH_SHORT) .show(); db = new DbAdapter_GPS(context); db.open(); android_id = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID); Log.i("MobileViaNetReceiver", "Android id is _ _ _ _ _ _" + android_id); locmgr = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); locmgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, onLocationChange); } LocationListener onLocationChange = new LocationListener() { public void onLocationChanged(Location loc) { // sets and displays the lat/long when a location is provided Log.i("MobileViaNetReceiver", "In onLocationChanged ....."); String latlong = "Lat: " + loc.getLatitude() + " Long: " + loc.getLongitude(); // Toast.makeText(this, latlong, Toast.LENGTH_SHORT).show(); Log.i("MobileViaNetReceiver", latlong); try { db.insertGPSCoordinates(android_id, Double.toString(loc.getLatitude()), Double.toString(loc.getLongitude())); } catch (Exception e) { Log.i("MobileViaNetReceiver", "db error catch _ _ _ _ " + e.getMessage()); } } public void onProviderDisabled(String provider) {} public void onProviderEnabled(String provider) {} public void onStatusChanged(String provider, int status, Bundle extras) {} }; //pauses listener while app is inactive /*@Override public void onPause() { super.onPause(); locmgr.removeUpdates(onLocationChange); } //reactivates listener when app is resumed @Override public void onResume() { super.onResume(); locmgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, onLocationChange); }*/ } 

Hay dos maneras de hacer esto:

  1. Utilice el método que es y registre un BroadcastReceiver que tenga un filtro de intenciones que coincida con el Intent que se mantenga dentro de su PendingIntent ( PendingIntent ) o, si sólo está interesado en un solo proveedor de ubicación, requestLocationUpdates (String provider, long minTime, float minDistance, PendingIntent intent) (1,5 +) en su lugar.
  2. Registre un LocaltionListener utilizando el requestLocationUpdates (String provider, long minTime, float minDistance, LocationListener listener) de LocationManager .

Pienso que usted está consiguiendo un poco confuso porque usted puede manejar la localización actualiza usando un BroadcastReceiver o un LocationListener – usted no necesita ambos. El método de registro de actualizaciones es muy similar, pero la forma en que los recibes es realmente muy diferente.

Un BroadcastReceiver permitirá que tu aplicación / servicio sea despertado aunque no esté en ejecución. Si cierra el servicio cuando no se está ejecutando, se reducirá considerablemente el impacto que tendrá en las baterías de los usuarios y se minimizará la posibilidad de que una aplicación de Task Killer termine el servicio.

Mientras que un LocationListener le exigirá que mantenga su servicio funcionando de lo contrario su LocationListener morirá cuando su servicio se cierra. Te arriesgas a las aplicaciones de Task Killer que matan tu servicio con un prejuicio extremo si usas este enfoque.

De su pregunta, sospecho que usted necesita utilizar el método BroadcastReceiver .

 public class MobileViaNetReceiver extends BroadcastReceiver { private static final String TAG = "MobileViaNetReceiver"; // please @Override public void onReceive(Context context, Intent intent) { if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())){ Log.i(TAG, "Boot : registered for location updates"); LocationManager lm = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); Intent intent = new Intent(context, this.getClass()); PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000,5,pi); } else { String locationKey = LocationManager.KEY_LOCATION_CHANGED; if (intent.hasExtra(locationKey)) { Location loc = (Location) intent.getExtras().get(locationKey); Log.i(TAG, "Location Received"); try { DbAdapter_GPS db = new DbAdapter_GPS(context);//what's this db.open(); String android_id = Secure.getString( context.getContentResolver(), Secure.ANDROID_ID); Log.i(TAG, "Android id is :" + android_id); db.insertGPSCoordinates(android_id, Double.toString(loc.getLatitude()), Double.toString(loc.getLongitude())); } catch (Exception e) { // NEVER catch generic "Exception" Log.i(TAG, "db error catch :" + e.getMessage()); } } } } } 
FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.