Search code examples
javaandroidbroadcastreceiverandroid-broadcastreceiver

Android - Register/Unregister Receiver Dynamically using a Helper Class with Static Methods?


THE SITUATION:
I have a 'helper' class with static methods, to dynamically enable/disable a BroadcastReceiver.
I call these methods from other classes, when I need to register (or) unregister the Receiver.

THE ISSUE:
I can't figure out how to dynamically UNRegister the receiver from within the helper class..
(When I try to do context.unregisterReceiver(myReceiver); it doesn't recognize myReceiver).

THE QUESTION:
How do I properly reference myReceiver from the receiverUnregister method in the Code below?


public class GpsReceiverHelper {


    //  Called from a different Class when I need to Register the Receiver
    public static void receiverRegister(Context context) {

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.location.PROVIDERS_CHANGED");

        final BroadcastReceiver myReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //  Receiver code goes here    
            }
        };
        context.registerReceiver(myReceiver, intentFilter);
    }



    //  Called from a different Class when I need to UN-Register the Receiver
    public static void receiverUnregister(Context context) {

        //  THIS DOESN'T WORK BECAUSE "myReceiver" can't be found..
        context.unregisterReceiver(myReceiver);

    }


}


Again, I plan to call these Methods from within a different class.
What is the proper way to go about doing this, and properly assign everything?


Solution

  • I managed to solve my issue by adding Field entries for static BroadcastReceiver myReceiver and then assigning it like myReceiver= ... inside of my static method containing the actual BroadcastReceiver code.. Furthermore, I realized I could avoid the BroadcastReceiver being killed upon calling finish(); simply by replacing context.registerReceiver with context.getApplicationContext.registerReceiver. Problem(s) solved!