Android BroadcastReceiver onReceive()在android 4.0上被调用了两次 [英] Android BroadcastReceiver onReceive() called twice on android 4.0
问题描述
我在android 4.0.3上遇到了一个问题(在4.1.2上工作正常). 我的活动BroadcastReceiver中有.当我发送广播时,方法onReceive()总是调用两次.请给我有关4.0和4.1上的BroadcastReceiver差异的任何建议
I faced to one problem on android 4.0.3 (on 4.1.2 it works fine). I have in my Activity BroadcastReceiver. When I send a broadcast, method onReceive() called always twice. Please give me any suggestions about BroadcastReceiver differences on 4.0 and 4.1
private final GcmBroadcastReceiver gcmReceiver = new GcmBroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action != null && action.equals(MyBroadcastReceiver.ACTION)) {
Log.d("tag", intent.getStringExtra("alert"));
}
}
};
};
@Override
protected void onPause() {
unregisterReceiver(gcmReceiver);
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
registerGcmReceiver();
}
private void registerGcmReceiver() {
IntentFilter filter = new IntentFilter(MyBroadcastReceiver.ACTION);
filter.setPriority(2);
filter.addCategory("com.android.mypackage");
registerReceiver(gcmReceiver, filter);
}
推荐答案
简短的回答:没有区别.两者的BroadcastReceiver
类来自Android 2.3.2 r1.
Short answer: there isn't a difference. The BroadcastReceiver
class for both is from Android 2.3.2 r1.
我也遇到过类似的问题,但对我来说,这是安装了Android 2.3.5的HTC Desire HD-来自GCM的通知将始终收到两次.我没有找到问题的根源,但是有一种解决方法.您可以为服务器中的每个通知生成唯一的ID,并将其与实际数据一起发送.然后,在您的接收器中,您可以更新唯一ID与通知数据的映射,如果给定ID已存在数据,则将其忽略.
I've had a similar problem, but for me it was with an HTC Desire HD with Android 2.3.5 on it - the notifications from GCM would always get received twice. I didn't manage to find the root of the problem, but there is a workaround. You can generate a unique ID for each notification in the server and send it along with the actual data. Then, in your receiver, you can update a mapping of unique ID to notification data, and if there is already data for the given ID, just ignore it.
我可能不太清楚,所以这是一个例子:
I probably didn't make that very clear, so here's an example:
public void onReceive(Context context, Intent intent) {
String id = intent.getStringExtra("notificationID");
if (myMap.get(id) != null)
return;
final String action = intent.getAction();
if (action != null && action.equals(MyBroadcastReceiver.ACTION)) {
Log.d("tag", intent.getStringExtra("alert"));
myMap.put(id, *any value you need*);
}
}
如果您不需要存储其他数据,则可以使用HashSet代替Map,只需检查其中是否包含ID.
If you don't need to store additional data, you can use a HashSet instead of a Map and just check if it contains the ID.
这篇关于Android BroadcastReceiver onReceive()在android 4.0上被调用了两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!