I believe this works in conjunction with BroadcastReceiver . You can set the addProximityAlert() method to run the onReceive() method on this receiver, which will provide you with Intent as a parameter, and then get an extra Boolean called KEY_PROXIMITY_ENTERING . So, step by step:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // You need to declare an Intent for your class and declare a PendingIntent on it, // so it might be passed to the addProximityAlert method as the fifth parameter. Intent intent = new Intent("com.yourdomain.yourproject.MyAlert"); PendingIntent proxIntent = PendingIntent.getBroadcast(this, 0, intent, 0); lm.addProximityAlert(your_latitude, your_longitude, RADIUS_IN_METERS, -1, proxIntent);
Explanation of the parameters set here:
- your_longitude : the longitude you want to calculate the radius
- your_latitude : the latitude you want to calculate the radius
- RADIUS_IN_METERS . This is a constant that you define, where you specify the length of the radius you want to track from the coordinate defined by the above parameters. If you set it to
1000 , for example, you say that if someone KEY_PROXIMITY_ENTERING closer to your coordinate closer than 1 km, KEY_PROXIMITY_ENTERING will be true if the previous execution of onReceive() was more distant than 1 km, and similarly otherwise . - -1 . This is the time in milliseconds after which the proximity warning will stop. If set to
-1 , it will never expire. - proxIntent : The
Intent affinity that will launch your BroadcastReceiver .
In addition, you will also need the following:
IntentFilter filter = new IntentFilter("com.yourdomain.yourproject.MyAlert"); registerReceiver(new AlertOnProximityReceiver(), filter);
This way you activate the receiver for the selected filter. This will fire the onReceive() event. So now there is only one left, declare BroadcastReceiver .
public class AlertOnProximityReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) { Boolean getting_closer = intent.getBooleanExtra(LocationManager.KEY_PROXIMITY_ENTERING, false); if (getting_closer) Log.d("Radius", "Hey, I just entered your radius!"); else Log.d("Radius", "I just exited your radius!"); } }
---- UPDATE ----
Now I see this in the documentation:
Gives out
SecurityException if ACCESS_FINE_LOCATION permission is missing
So make sure you include this permission in your AndroidManifest.xml file.