在文档中,在讨论时addProximityAlert,关于Intent的描述让我感到困惑.具体这部分..
触发的Intent将使用键KEY_PROXIMITY_ENTERING添加一个布尔额外的.如果值为true,则设备进入邻近区域; 如果错误,它就会退出.
这可能听起来像一个愚蠢的问题但是......当我进入/或在某个位置的某个半径时,我如何得到真或假.
我不确定这是如何工作的.
我是否必须编写自己的代码并检查我何时在我的位置附近,然后在我退出时让它返回true和false?
我无法弄清楚.
我相信这与a一起使用BroadcastReceiver.您可以将addProximityAlert()方法设置为onReceive()在此接收器上触发方法,该方法将为您提供Intent一个参数,然后获取该额外Boolean调用KEY_PROXIMITY_ENTERING.所以,一步一步:
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);
Run Code Online (Sandbox Code Playgroud)
解释这里设置的参数:
1000,你是说,如果有人越来越近1公里多到你的协调,该KEY_PROXIMITY_ENTERING会是true,如果上一次执行onReceive()是更遥远的超过1公里,否则类似.-1,它将永不过期.Intent你的火力BroadcastReceiver.此外,您还需要:
IntentFilter filter = new IntentFilter("com.yourdomain.yourproject.MyAlert");
registerReceiver(new AlertOnProximityReceiver(), filter);
Run Code Online (Sandbox Code Playgroud)
这样您就可以为刚设置的过滤器激活Receiver.这将触发onReceive()事件.现在,只剩下一件事了,宣布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!");
}
}
Run Code Online (Sandbox Code Playgroud)
----更新----
我现在在文档中看到这个:
抛出
SecurityException如果不存在ACCESS_FINE_LOCATION权限
因此,请确保在您的AndroidManifest.xml文件中包含此权限.
| 归档时间: |
|
| 查看次数: |
2016 次 |
| 最近记录: |