问题描述
在我的应用中,我有多个地理围栏,并且我希望它们具有唯一的待处理意图,并带有不同的额外数据.但是正在发生的事情是,对于我所有的地理围栏,正在触发的待定意图都是为最后一个地理围栏添加的,而不是分配给用户刚刚迷惑的特定地理围栏的一个.
In my app I have multiple geofences and I want them to have unique pending intents, with different extra data. But what is happenning is that for all my geofences pending intents that are being triggered are one that was added for last geofence and not one that was assigned to the specific one the user just enetered.
因此,例如,当我有2个地理围栏,而对于第一个地理围栏,我会向待处理的意图中添加额外的字符串"AAA",然后添加额外的"BBB"来添加第二个地理围栏 并输入第一个地理围栏,我将收到"BBB"而不是正确的"AAA"的通知我究竟做错了什么?这是我的代码,在其中我添加了一个新的地理围栏:
So for example when I would have 2 geofences and for first one I would add extra string "AAA" to pending intent, then add second geofence with extra "BBB" and enter first geofence I would get notification with "BBB" instead of correct "AAA"What am I doing wrong? Here is my code where I add single new geofence:
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
和
I see you are using a generic function to build your PendingIntents
and
return PendingIntent.getService(context, 0, intent, FLAG_UPDATE_CURRENT);
将ID 0
指定为您要构建的任何PendingIntent
.
specifies the ID 0
to whatever PendingIntent
you are building.
由于使用的是标志FLAG_UPDATE_CURRENT
,因此您将覆盖以前构建的PendingIntent
(AAA
).
Since you are using the flag FLAG_UPDATE_CURRENT
, you are just overriding the previously built PendingIntent
( AAA
).
在这两个Intents
之间唯一改变的是额外功能,但没有考虑到它们:请参阅 Android如何比较PendingIntents .
Extras is the only thing that changes between the two Intents
but they are not taken into consideration: see how Android compares PendingIntents.
答案:为每个PendingIntent
使用不同的requestCode
.
Answer: use a different requestCode
for each PendingIntent
.
这篇关于地理围栏,触发了错误的挂起意图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!