Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 443
ProNeticas Avatar asked Mar 09 '11 01:03

ProNeticas


People also ask

When would you use a BroadcastReceiver?

Broadcast in android is the system-wide events that can occur when the device starts, when a message is received on the device or when incoming calls are received, or when a device goes to airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events.

How do I check if BroadcastReceiver is registered?

public boolean isReceiverRegistered(BroadcastReceiver receiver); It would return true if it's registered and false if not.

Where do I register and unregister broadcast receiver?

Receiver can be registered via the Android manifest file. You can also register and unregister a receiver at runtime via the Context. registerReceiver() and Context. unregisterReceiver() methods.


1 Answers

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!

like image 82
devunwired Avatar answered Oct 21 '22 11:10

devunwired