Wednesday, April 25, 2012

how to check if Receiver is registered in android


I need to check if my registered receiver is still registered if not how do i check it any methods?



Source: Tips4all

3 comments:

  1. I am not sure the API provides directly an API, if you consider this thread:


    I was wondering the same thing.
    In my case I have a BroadcastReceiver implementation that calls
    Context#unregisterReceiver(BroadcastReceiver) passing itself as the arg after handling the Intent that it receives.
    There is a small chance that the receiver's onReceive(Context, Intent) method is called
    more than once, since it is registered with multiple IntentFilters, creating the potential for an IllegalArgumentException being thrown from Context#unregisterReceiver(BroadcastReceiver).

    In my case I can store a private synchronized member to check before calling Context#unregisterReceiver(BroadcastReceiver), but it would be
    much cleaner if the API provided a check method.

    ReplyDelete
  2. There is no API function to check if a receiver is registered. The workaround is to put your code in a try {...} catch(IllegalArgumentException e) {...} block.

    ReplyDelete
  3. You have several options


    You can put a flag into your class or activity. Put a boolean variable into your class and look at this flag to know if you have the Receiver registered.
    Create a class that extends the Receiver and there you can use:


    Singleton pattern for only have one instance of this class in your project.
    Implement the methods for know if the Receiver is register.

    ReplyDelete