防止多次接收广播
我在广播中使用这种设置:
IntentFilter filter = new IntentFilter("com.commonsware.cwac.tlv.demo.onlineDbResult");
filter.addCategory(INTENT_CATEGORY);
ResultReceiver receiver= new ResultReceiver();
registerReceiver(receiver, filter);
并调用接收者:
Intent resultIntent = new Intent("com.commonsware.cwac.tlv.demo.onlineDbResult");
if(categories!=null){
for(String category:categories){
resultIntent.addCategory(category);
Log.d(TAG,"add category "+category);
}
}
不知何故,以这种方式注册的接收者多次接收意图(2或3次),这是为什么?
com.commonsware.cwac.tlv.demo 是命名空间, onlineDbResult 只是一个附加字符串,而不是类或任何东西。
接收时:
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
String result = extras.getString("result");
Log.d("baby","Register received result "+result);
if(progressDialog!=null)
progressDialog.dismiss();
if(result.equals("user_added")){
do stuff
I use this kind of set up for my broadcasts:
IntentFilter filter = new IntentFilter("com.commonsware.cwac.tlv.demo.onlineDbResult");
filter.addCategory(INTENT_CATEGORY);
ResultReceiver receiver= new ResultReceiver();
registerReceiver(receiver, filter);
And the to call the receiver:
Intent resultIntent = new Intent("com.commonsware.cwac.tlv.demo.onlineDbResult");
if(categories!=null){
for(String category:categories){
resultIntent.addCategory(category);
Log.d(TAG,"add category "+category);
}
}
Somehow the receiver registered in this way receives the intent multiple times (2 or three times) why is this?
com.commonsware.cwac.tlv.demo is the namespace, onlineDbResult is just an appended string not a class or anything.
The onReceive:
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
String result = extras.getString("result");
Log.d("baby","Register received result "+result);
if(progressDialog!=null)
progressDialog.dismiss();
if(result.equals("user_added")){
do stuff
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
检查您是否正确取消注册接收器,即在 onDestroy() 上,否则您可能会收到相同的 Intent 两次。
Check if you're unregistering the receiver properly, i.e. on onDestroy(), otherwise you may receive the same Intent twice.
您注册了多个接收器,或者广播了多个
Intent
。请注意,我不知道你为什么要在广播中搞乱类别。类别主要与活动一起使用。
Either you registered multiple receivers or you broadcast multiple
Intents
.Note that I have no idea why you are messing around with categories with your broadcasts. Categories are mostly used with activities.
回到这一点,我认为我的问题可能是我混合了类别和操作。过滤器匹配类别和操作,并分别捕获这两个原因的意图,触发 onReceive 两次。但我不确定。为了防止这种情况,请就是否使用类别或操作做出明智的决定
Coming back to this, I think my problem might have been that I mixed categories and actions. The filter matched the categoty AND the action, and caught the intent for both reasons separately, firing onReceive twice. But I am unsure. To prevent this, make informed decisions on wether to use categories or actions