Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

registerReceiver for Broadcast only if it's not already registered?

Tags:

android

I have a snippet of code that I'm calling from a service:

context.registerReceiver(new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            WifiManager mWm = (WifiManager) context
                    .getSystemService(Context.WIFI_SERVICE);
            ret = mWm.isWifiEnabled();
            // DO MORE STUFF HERE
        } catch (Exception e) {
        }
    }
}, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));

What I would like is a way to check and make sure that the registerReceiver isn't already listening before it calls it again. Is this possible?

For example if my snippet of code is in a method, and I call the method 10 times, right now the onReceive method appears to run 10 times.

like image 538
Cameron McBride Avatar asked Jan 26 '10 17:01

Cameron McBride


People also ask

How do you check broadcast receiver is registered or not?

A simple solution to this problem is to call the registerReceiver() in your Custom Application Class. This will ensure that your Broadcast receiver will be called only one in your entire Application lifecycle.

Where do I register and unregister broadcast receiver?

You should register and unregister your broadcast in onResume() and onPause() methods. if you register in onStart() and unregister it in onStop().

How do I register a broadcast receiver in manifest?

There are two ways to make a broadcast receiver known to the system: One is declare it in the manifest file with this element. The other is to create the receiver dynamically in code and register it with the Context. registerReceiver() method.


1 Answers

There isn't a way of finding out — you should only be calling registerReceiver once, most likely upon the creation of your service.

You need to keep a reference to the BroadcastReceiver too for when you call unregisterService (onDestroy() is the natural place for it), otherwise the system will warn you about leaking broadcast receivers and get angry and possibly shout at you.

like image 179
Christopher Orr Avatar answered Nov 15 '22 17:11

Christopher Orr