地理围栏,错误的未决意图被触发

Geofencing, wrong pending intent is being triggered

在我的应用程序中,我有多个地理围栏,我希望它们具有独特的待处理意图和不同的额外数据。但是正在发生的事情是,对于我所有正在触发的地理围栏未决意图,都是为最后一个地理围栏添加的意图,而不是分配给用户刚刚输入的特定意图的意图。

因此,例如,当我有 2 个地理围栏时,对于第一个地理围栏,我会向未决意图添加额外的字符串 "AAA",然后添加第二个带有额外 "BBB" 的地理围栏 然后输入第一个地理围栏,我会收到 "BBB" 的通知,而不是正确的 "AAA" 我究竟做错了什么?这是我添加单个新地理围栏的代码:

public void addGeofencing(final MyObject myObject){

    Geofence geofence = (new Geofence.Builder()
            .setRequestId(myObject.getId())

            .setCircularRegion(
                myObject.getLat(),
                myObject.getLon(),
                RADIUS_IN_METERS
            )
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
                            Geofence.GEOFENCE_TRANSITION_EXIT)
            .setExpirationDuration(Geofence.NEVER_EXPIRE)
            .build());

            client.addGeofences(getGeofencingRequest(geofence),getGeofencePendingIntent(myObject.getExtraString))
                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            System.out.println("GEOFENCE WORKED");
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    System.out.println("GEOFENCE FAILED");
                }
            });

    }

    private GeofencingRequest getGeofencingRequest(Geofence geofence) {
        GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
        builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
        builder.addGeofence(geofence);
        return builder.build();
    }
    private PendingIntent getGeofencePendingIntent(String extraString) {
        Intent intent = new Intent(context, GeofenceTransitionsIntentService.class);
        intent.putExtra("extra",extraString);
        return PendingIntent.getService(context, 0, intent, FLAG_UPDATE_CURRENT);
    }

我看到您正在使用通用函数来构建您的 PendingIntents

return PendingIntent.getService(context, 0, intent, FLAG_UPDATE_CURRENT);

将 ID 0 指定给您正在构建的任何 PendingIntent

由于您使用的是标志 FLAG_UPDATE_CURRENT,因此您只是覆盖了之前构建的 PendingIntent ( AAA )。

Extras 是两者之间唯一发生变化的东西 Intents 但它们没有被考虑在内:看看如何 .


答案:每个PendingIntent使用不同的requestCode