java - 如何将数据从活动传递到地理围栏广播接收器?
问题描述
我正在构建一个地理围栏应用程序来跟踪给定区域在任何给定时间的人数并将他们的 ID 存储在后端。我无法弄清楚如何将我从用户GeofenceBroadcastReceiver
那里获取的 ID 传递到我在其中增加和减少人数的地方,onReceive
这样我就可以跟踪那里的所有人。我不认为它可以通过意图传递,因为我不是调用接收者的人,而且我不熟悉该过程的内部运作。
MainActivity.java
public void addGeofence(LatLng latLng, float radius) {
Geofence geofence = geofenceHelper.getGeofence(GEOFENCE_ID, latLng, radius, Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_DWELL | Geofence.GEOFENCE_TRANSITION_EXIT);
GeofencingRequest geofencingRequest = geofenceHelper.getGeofencingRequest(geofence);
PendingIntent pendingIntent = geofenceHelper.getPendingIntent();
geofencingClient.addGeofences(geofencingRequest, pendingIntent).addOnSuccessListener(
\\code );
地理围栏助手.java
public class GeofenceHelper extends ContextWrapper {
PendingIntent pendingIntent;
public GeofenceHelper(Context base) {
super(base);
}
public GeofencingRequest getGeofencingRequest(Geofence geofence) {
return new GeofencingRequest.Builder()
.addGeofence(geofence)
.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
.build();
}
public Geofence getGeofence(String ID, LatLng latLng, float radius, int transitionTypes) {
return new Geofence.Builder()
.setCircularRegion(latLng.latitude, latLng.longitude, radius)
.setRequestId(ID)
.setTransitionTypes(transitionTypes)
.setLoiteringDelay(5000)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build();
}
public PendingIntent getPendingIntent() {
if (pendingIntent != null) {
return pendingIntent;
}
Intent intent = new Intent(this, GeofenceBroadcastReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
解决方案
无需将数据从活动传递到GeofenceBroadcastReceiver
. 当用户进入地理围栏区域时,GeofenceBroadcastReceiver onReceive()
如果您正确注册了地理围栏,Android系统将自动调用。
添加成功后,首先注册您的地理围栏,在您的模拟器中设置您注册的地理围栏位置并四处移动以触发地理围栏的进入和退出。触发时,onReceive()
将自动调用,您可以从onReceive()
意图中获取触发 id。然后你可以增加和减少人数onReceive()
推荐阅读
- node.js - 使用 TypeScript 时,在 Node.js 客户端库中为 Google v2 上的操作扩展“conv”实例
- php - 数组到 HTML 表,调整很少
- node.js - MissingSchemaError:尚未为模型“用户”注册架构。尝试在 CLI 上执行代码时
- javascript - 如何将 Jquery Datatables Ellipsis 渲染器用于模板字段链接按钮?
- elasticsearch - Logstash 和 Elasticsearch 配置
- ruby-on-rails - 如何在 Json 中连接两个字段 - Ruby
- firebase - 为什么在 Kotlin 中迭代 firebase 数据库时元素值添加了两次?
- mysql - MySQL GROUP_CONCAT 与内部 CONCAT 剪切值?无关紧要的结果
- google-sheets - 谷歌表格将单元格组合成标准
- authentication - 两因素身份验证不起作用:SMS 没有联系到我