【问题标题】:Geofencing, wrong pending intent is being triggered地理围栏,正在触发错误的未决意图
【发布时间】:2018-02-26 10:08:54
【问题描述】:

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

因此,例如,当我有 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);
    }

【问题讨论】:

    标签: android android-pendingintent android-geofence


    【解决方案1】:

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

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

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

    由于您使用的是标志FLAG_UPDATE_CURRENT,因此您只是覆盖了先前构建的PendingIntentAAA)。

    Extras 是两个 Intents 之间唯一的变化,但它们没有被考虑在内:看看 Android compares PendingIntents 是如何变化的。


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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-03
      • 1970-01-01
      • 2016-01-01
      • 1970-01-01
      • 2015-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多