Search code examples
androidbroadcastreceiver

How to unregister a broadcast receiver properly


i followed this answer to register a receiver and it works perfect.Here now i wonder how to unregister it in the ondestroy?


Solution

  • Unregistering the broadcast receiver is simple, you call unregisterReceiver method and pass the broadcast receiver to it.

    Based on the answer you've shared

    1) Change the registering of broadcast receiver in the onCreate method to

    registerReceiver(gpsReceiver, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
    

    2) Declare a global variable

    final BroadcastReceiver gpsReceiver = new GpsReceiver(new LocationCallBack() {
            @Override
            public void onLocationTriggered() {
                //Location state changed
            }
        });
    

    3) In the onDestroy, Unregister the broadcast receiver

    unregisterReceiver(gpsReceiver);