BroadcastReceiver for location
I know BroadcastReceiver watches for text, phone events, etc... but can you run LocationServices as a service 开发者_开发问答and event based on Location?
For example, you are near a certain GPS point and the phone notifies you.
I think what you are looking for is something like this. There is a version of LocationManager.requestLocationUpdates()
that takes a PendingIntent
as a parameter, and this Intent could be used to fire a BroadcastReceiver
. This code will register a custom broadcast to fire with the location updates.
Intent intent = new Intent("UNIQUE_BROADCAST_ACTION_STRING_HERE");
LocationManager manager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
long minTime; //This should probably be fairly long
float minDistance; //This should probably be fairly big
String provider; //GPS_PROVIDER or NETWORK_PROVIDER
PendingIntent launchIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
manager.requestLocationUpdates(provider, minTime, minDistance, launchIntent);
Then you just have to register your BroadcastReceiver
with the same Intent action and it will receive the location updates for processing. And, of course, keep that PendingIntent
around because you'll need to call manager.removeUpdates(launchIntent)
at some point!
Final Note:
Because it sounds like you are trying to implement regular location updates while your app isn't in the foreground, keep this in mind. Unless you want your app branded as a battery killer, be extremely careful with how you implement this functionality.
You will want to greatly reduce the frequency up location updates with either a large minTime or minDistance parameter to allow the location service to rest. This feature should also be attached to a user controlled preference so they can enable/disable your app from tracking location in the background.
Hope that Helps!
This question is more then 2 years old but there is now very very easy and battery efficient way to do this. The concept is called Geofences. You can learn it in more detail below:
http://developer.android.com/training/location/geofencing.html
精彩评论