【问题标题】:How can I pass data from an Activity to a Geofence BroadcastReceiver?如何将数据从活动传递到地理围栏广播接收器?
【发布时间】:2021-05-30 11:43:20
【问题描述】:

我正在构建一个地理围栏应用程序来跟踪给定区域在任何给定时间的人数并将他们的 ID 存储在后端。 我无法弄清楚如何将我从用户那里获取的 ID 传递给 GeofenceBroadcastReceiver,我正在增加和减少 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 );

GeofenceHelper.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;
    }

【问题讨论】:

    标签: java android geofencing android-geofence


    【解决方案1】:

    无需将活动中的数据传递给GeofenceBroadcastReceiver。当用户进入地理围栏区域时,如果您正确注册了地理围栏,Android系统将自动调用GeofenceBroadcastReceiver onReceive()

    添加成功后首先注册您的地理围栏,在您的模拟器中设置您注册的地理围栏位置并四处移动以触发地理围栏的进入和退出。触发时,onReceive() 会自动被调用,您可以从onReceive() 意图中获取触发的 id。然后你可以增加和减少onReceive()的人数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多