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

微笑、不失礼 提交于 2019-12-06 07:01:50

问题


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


回答1:


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>



回答2:


You can find a good example here: http://www.java2s.com/Code/Android/Core-Class/ProximityAlertDemo.htm



来源:https://stackoverflow.com/questions/15192347/android-how-to-set-a-proximity-alert-to-fire-only-when-exiting-or-only-when-ent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!