首页 > 解决方案 > 如何将数据从活动传递到地理围栏广播接收器?

问题描述

我正在构建一个地理围栏应用程序来跟踪给定区域在任何给定时间的人数并将他们的 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;
    }

标签: javaandroidgeofencingandroid-geofence

解决方案


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

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


推荐阅读