How to create Dynamic broadcast receivers in Android?
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
- android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Register"
- android:id="@+id/registerButton"
- android:layout_marginTop="103dp"
- android:layout_alignParentTop="true"
- android:layout_centerHorizontal="true" />
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Send"
- android:id="@+id/sendButton"
- android:layout_below="@+id/registerButton"
- android:layout_centerHorizontal="true"
- android:layout_marginTop="99dp" />
- </RelativeLayout>
- intentFilter = new IntentFilter();
- intentFilter.addAction("tutorial.negociosit.com.tutorial6.TEST_BROADCAST");
Create a broadcast listener in the java class.
- private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- Toast.makeText(context,"This is the broadcast",Toast.LENGTH_SHORT).show();
- }
- };
In the java activity file register the broadcast receiver in the register button click listner, see the code below,
- registerButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- registerReceiver(broadcastReceiver,intentFilter);
- }
- });
Now see the code for sending broadcast in the send button click event,
- sendButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- Intent intent = new Intent();
- intent.setAction("tutorial.negociosit.com.tutorial6.TEST_BROADCAST");
- sendBroadcast(intent);
- }
- });
This is how we can create the broadcast receivers dynamically in Android. Please see the out put also.


Kuppurasu NagarajPosted May 17, 2016, 11:32 AM
Nice sharing..
Sonu ChaudharyPosted May 16, 2016, 3:31 PM
good one...
Prasanna MuraliPosted May 16, 2016, 10:08 AM
Nice one...