Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

android - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...