Search code examples
androidbroadcastreceiver

prevent receiving broadcasts multiple times


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

Solution

  • 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