防止多次接收广播

时间:2012-02-11 13:33:53

标签: android broadcastreceiver

我使用这种设置进行广播:

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只是一个附加字符串而不是类或任何东西。

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

3 个答案:

答案 0 :(得分:1)

检查您是否正确注销接收器,即onDestroy(),否则您可能会收到两次相同的Intent。

答案 1 :(得分:0)

  

不知何故,以这种方式注册的接收者多次接收意图(2或3次)为什么会这样?

您注册了多个接收器,或者您广播了多个Intents

请注意,我不知道您为什么要在广播中使用类别。类别主要用于活动。

答案 2 :(得分:0)

回到这一点,我认为我的问题可能是我混合了类别和行动。过滤器匹配了分类和动作,并分别捕获两个原因的意图,触发onReceive两次。但我不确定。为了防止这种情况,做出明智的决定,使用类别或行动