Home » Android » android – registerReceiver for Broadcast only if it's not already registered?

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

Posted by: admin June 15, 2020 Leave a comment

Questions:

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.

How to&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.

Answer:

What about something like this

class Thing {
    interface R {
        void onReceive(Context c, Intent i);
    }

    private BroadcastReceiver receiver;
    private IntentFilter filter;
    private boolean isRegistered = false;

    public Thing(Thing.R r, String... actions) {
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                r.onReceive(context, intent);
            }
        };
        filter = new IntentFilter();
        for (String a : actions)
            filter.addAction(a);
    }

    public void register(Context c) {
        if (isRegistered) return;
        c.registerReceiver(receiver, filter);
        isRegistered = true;
    }

    public void unregister(Context c) {
        if (!isRegistered) return;
        c.unregisterReceiver(receiver);
        isRegistered = false;
    }
}

then

Thing t = new Thing((c, i) -> {
    try {
        WifiManager mWm = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        ret = mWm.isWifiEnabled();
        // DO MORE STUFF HERE
    } catch (Exception e) {
    }
}, WifiManager.WIFI_STATE_CHANGED_ACTION);

now call t.register as many as you like!