What's the best way to create an app that periodically gets location (via the GPS or开发者_如何学C cell towers, or whatever) even when the app isn't running?
The first idea I had is to use the AlarmManager to wake up at a specified interval and check. I'm wondering if there's a more specific API to use.
You subscribe to get notification on LocationChanged. You will get a broadcast receiver that will wake up your app. You can launch activities from the BroadCast receiver using the passed context as launchpoint.
locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// loop through all providers, and register them to send updates
List<String> providers = locMan.getProviders(false);
for (String provider : providers) {
Log.e("mytag", "registering provider " + provider);
long minTimeMs = 5 * 60 * 1000;// 5 minute
float minDistance = LOCATION_HOT_RADIUS_IN_METERS;
locMan.requestLocationUpdates(provider, minTimeMs, minDistance,
getIntent());
}
private PendingIntent getIntent() {
Intent intent = new Intent(this, LocationReceiver.class);
return PendingIntent.getBroadcast(
getApplicationContext(), 0, intent, 0);
}
and the receiver
public class LocationReceiver extends BroadcastReceiver {
/*
* (non-Javadoc)
*
* @see android.content.BroadcastReceiver#onReceive(android.content.Context,
* android.content.Intent)
*/
@Override
public void onReceive(Context context, Intent intent) {
try {
Bundle b = intent.getExtras();
Location loc = (Location) b
.get(android.location.LocationManager.KEY_LOCATION_CHANGED);
if (loc != null) {
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
精彩评论