Android Requestlocationupdates Using Pendingintent With Broadcastreceiver
Solution 1:
There are two ways of doing this:
- Use the method that you are and register a
BroadcastReceiver
which has an intent filter which matches the Intent that is held within yourPendingIntent
(2.3+) or, if you are only interested in a single location provider,requestLocationUpdates (String provider, long minTime, float minDistance, PendingIntent intent)
(1.5+) instead. - Register a
LocaltionListener
using therequestLocationUpdates (String provider, long minTime, float minDistance, LocationListener listener)
method ofLocationManager
.
I think that you are getting a little confused because you can handle the location update using either a BroadcastReceiver
or a LocationListener
- you don't need both. The method of registering for updates is very similar, but how you receive them is really very different.
A BroadcastReceiver
will allow your app / service to be woken even if it is not currently running. Shutting down your service when it is not running will significantly reduce the impact that you have on your users' batteries, and minimise the chance of a Task Killer app from terminating your service.
Whereas a LocationListener
will require you to keep your service running otherwise your LocationListener
will die when your service shuts down. You risk Task Killer apps killing your service with extreme prejudice if you use this approach.
From your question, I suspect that you need to use the BroadcastReceiver
method .
Solution 2:
publicclassMobileViaNetReceiverextendsBroadcastReceiver {
privatestaticfinalStringTAG="MobileViaNetReceiver"; // please@OverridepublicvoidonReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())){
Log.i(TAG, "Boot : registered for location updates");
LocationManagerlm= (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
Intentintent=newIntent(context, this.getClass());
PendingIntentpi= PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000,5,pi);
} else {
StringlocationKey= LocationManager.KEY_LOCATION_CHANGED;
if (intent.hasExtra(locationKey)) {
Locationloc= (Location) intent.getExtras().get(locationKey);
Log.i(TAG, "Location Received");
try {
DbAdapter_GPSdb=newDbAdapter_GPS(context);//what's this
db.open();
Stringandroid_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());
}
}
}
}
}
Post a Comment for "Android Requestlocationupdates Using Pendingintent With Broadcastreceiver"