Home » Android » dynamic – Dynamically register/unregister a broadcast receiver in android

dynamic – Dynamically register/unregister a broadcast receiver in android

Posted by: admin June 15, 2020 Leave a comment

Questions:

I want to dynamically register and unregister my receiver class with the broadcast:
“android.net.wifi.STATE_CHANGE”
This works very well if I do this in the manifest. But this makes it static. I want to do it dynamically in the activity class. What is its correspondent command in the activity class?

This is what my code is…
and I am getting a problem because of registering and unregistering(multiple times) my receiver(which is starting a service).

public class startScreen extends Activity {
    /** Called when the activity is first created. */

    private BroadcastReceiver receiver = new BroadcastReceiver() {    

        @Override
        public void onReceive(Context context, Intent intent) {
            Intent serviceIntent = new Intent();
            serviceIntent.setAction("com.example.MyService");
            context.startService(serviceIntent);    
        }    
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.initial);

        final IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.wifi.STATE_CHANGE");   

        Button button = (Button) findViewById(R.id.button1);
        final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton1);

        try {
                ...some code...
            if (bool == true) {
                toggleButton.setChecked(true);
                this.registerReceiver(receiver, filter);
            } else
                toggleButton.setChecked(false);
        } catch (Exception e) {
            Log.e("Error", "Database", e);
        } finally {
                ...
        }

        toggleButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if ((toggleButton.isChecked())) {
                    getBaseContext().registerReceiver(receiver, filter);

                } else {
                    if (receiver != null) {
                        getBaseContext().unregisterReceiver(receiver);
                        receiver = null;
                    }

                }
            }
        });
    }    

    @Override
    protected void onResume() {
        super.onResume();
        if (bool == true) {
            if (receiver == null)
                this.registerReceiver(receiver, filter);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (receiver != null) {
            this.unregisterReceiver(receiver);
            receiver = null;
        }
    }
}
How to&Answers:

The LocalBroadcastManager class is used to register for and send broadcasts of Intents to local objects within your process. This is faster and more secure as your events don’t leave your application.

The following example shows an activity which registers for a customer event called my-event.

@Override
public void onResume() {
super.onResume();

   // Register mMessageReceiver to receive messages.
   LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
     new IntentFilter("my-event"));
}

// handler for received Intents for the "my-event" event 
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
   // Extract data included in the Intent
   String message = intent.getStringExtra("message");
   Log.d("receiver", "Got message: " + message);
 }
};

@Override
protected void onPause() {
   // Unregister since the activity is not visible
   LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
   super.onPause();
} 
// This method is assigned to button in the layout
// via the onClick property
public void onClick(View view) {
   sendMessage();
}

// Send an Intent with an action named "my-event". 
private void sendMessage() {
  Intent intent = new Intent("my-event");
  // add data
  intent.putExtra("message", "data");
  LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
} 

Answer:

use the below methods to register/unregister your receiver:

registerReceiver(BroadcastReceiver receiver, new IntentFilter("android.net.wifi.STATE_CHANGE"));
unregisterReceiver(BroadcastReceiver receiver);

For reference have a look at this

Answer:

Don’t add dynamic broadcast receiver in onReceive on broadcast file. Add it on first activity or main activity of your application. If you needed it only when your application is open. But if you need it always received response just added it on manifest file

Register dynamic broadcast receiver on main activity

MyReceiver reciver;

@Override
protected void onResume() {
    super.onResume();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
    intentFilter.addAction("android.net.wifi.STATE_CHANGE");
    reciver = new MyReceiver();
    registerReceiver(reciver, intentFilter);
}

Unregister that broadcast receiver on activity stop or closed

@Override
protected void onStop() {
    super.onStop();
    unregisterReceiver(reciver);
}

Answer:

Perhaps I’m a bit too late, but the problem lies on the fact that you are setting the receiver = null in your onPause method, and then never setting it again. You are also trying to register it in your onResume method but only if it is null, which makes no sense too.

You should change the logic where you set/test the null value of the receiver, to instead just use a boolean variable to keep track of the receiver status (if it’s registered or not).

Answer:

public void registerBroadcastReceiver(View view) {

    this.registerReceiver(broadCastReceiver, new IntentFilter(
        "android.intent.action.TIME_TICK"));
}


public void unregisterBroadcastReceiver(View view) {

    this.unregisterReceiver(broadCastReceiver);
}