Android: how to set a proximity alert to fire only when exiting or only when entering the location

Daniel picture Daniel · Mar 4, 2013 · Viewed 7.9k times · Source

I am developing a ToDo app with reminders(by time and by location) and the thing is I give the user the option to choose if he wants the reminder by location to alert when he is entering the location or when he exits the location. how can i do that??

I know about the KEY_PROXIMITY_ENTERING but I dont know how to use it Please help... thanx in advance

Answer

StarPinkER picture StarPinkER · Mar 4, 2013

The KEY_PROXIMITY_ENTERING is usually used to determine whether the device is entering or exiting.

You should first register to the LocationManager

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Intent intent = new Intent(Constants.ACTION_PROXIMITY_ALERT);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);

locationManager.addProximityAlert(location.getLatitude(),
    location.getLongitude(), location.getRadius(), -1, pendingIntent);

The PendingIntent will be used to generate an Intent to fire when entry to or exit from the alert region is detected. You should define a broadcast receiver to receive the broadcast sent from LocationManager:

public class YourReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        final String key = LocationManager.KEY_PROXIMITY_ENTERING;
        final Boolean entering = intent.getBooleanExtra(key, false);

        if (entering) {
            Toast.makeText(context, "entering", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(context, "exiting", Toast.LENGTH_SHORT).show();
        }
    }
}

Then register the receiver in your manifest.

<receiver android:name="yourpackage.YourReceiver " >
    <intent-filter>
        <action android:name="ACTION_PROXIMITY_ALERT" />
    </intent-filter>
</receiver>