Ccna final exam - java, php, javascript, ios, cshap all in one. This is a collaboratively edited question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
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?
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.
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.
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.
I am not sure the API provides directly an API, if you consider this thread:
ReplyDeleteI 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.
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.
ReplyDeleteYou have several options
ReplyDeleteYou 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.