安卓:如何设置接近警报仅在离开或进入位置时触发

3

我正在开发一个带有提醒功能的ToDo应用程序(根据时间和地点),让用户选择是否希望在进入或离开某个位置时进行提醒。 如何实现这一功能?

我知道KEY_PROXIMITY_ENTERING,但我不知道如何使用它。 请帮忙... 先感谢了。

2个回答

6

KEY_PROXIMITY_ENTERING通常用于确定设备是进入还是退出。

您应该首先向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);

当检测到进入或离开警报区域时,PendingIntent将用于生成Intent来触发操作。您应该定义一个广播接收器来接收从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();
        }
    }
}

然后在您的清单文件中注册接收器。

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

另一个问题 - 我的接收器已经处理了按时间提醒的广播。我如何定义哪个提醒触发了该操作?它们都是从同一个类中触发的 - @Jermaine Xu - Daniel
顺便说一句,感谢关于主要问题的答案。看起来这就是答案 - @Jermaine Xu - Daniel
我认为你想要的是 intent.getAction(),对吗? - StarPinkER
所以在XML文件中的intent-filter属性中,我需要有两个<action>属性吗?一个是用于“按时间提醒”,另一个是用于“按位置提醒”?@Jermaine Xu - Daniel
这个答案旨在说明如何在设备接近或退出区域时获得通知。因此,如果您想要禁用警报,请将一些代码放入上面示例中的“else”区域。如果您想知道如何显示警报,则最好提出另一个问题。 - StarPinkER
显示剩余2条评论

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接