How to implement BroadcastReceiver in Android

Broadcast Receiver is an Android component which allows the users to register for an event and triggers when the event happens. A receiver can be registered for pre-defined Android actions or custom actions.

To implement the Broadcast Receiver in Android Application:

  1. Define a Broadcast Register.(can be done in two ways i.e one is locally in Activity class and second is Define Custom Broadcast as a class)
  2. Register the receiver for particular events.(can be done in two ways i.e one is to register receiver in an activity and other is register receiver in AndroidManifest file)
  3. The receiver gets triggered once the event happens or when a custom broadcast is sent.

Note: If we register the receiver in AndroidManifest.xml file it will also trigger if the application is killed/ not alive but if we register the receiver in Activity it will only till the application is live.

We can define the receiver locally in a class or can define the Broadcast Receiver class explicitly.

To define the broadcast receiver explicitly.

I have defined the class as MyBroadcastReceiver and showed a toast in the onReceive method.

public class MyBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"Broadcast Received",Toast.LENGTH_SHORT).show();
    }
}

To define the Broadcast receiver in Activity class.

public class MainActivity extends AppCompatActivity {

    BroadcastReceiver receiver;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        receiver=new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Toast.makeText(context,"Broadcast Received in Activity called ",Toast.LENGTH_SHORT).show();
            }
        };
    }
}

 To register a Receiver in AndroidManifest.xml file

<receiver android:name=".MyBroadcastReceiver">
            <intent-filter>
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
            </intent-filter>
        </receiver>

 To register a Receiver in Activity class

to register locally defined receiver.

// to register local receiver
  filter = new IntentFilter();
  // specify the action to which receiver will listen
  filter.addAction("com.local.receiver");
  registerReceiver(receiver,filter);

to register custom receiver.

//to Register custom Broadcast Receiver defined in separate class
       MyBroadcastReceiver myBroadcastReceiver=new MyBroadcastReceiver();
       IntentFilter filter1=new IntentFilter();
       filter1.addAction("Intent.ACTION_POWER_CONNECTED");
       registerReceiver(myBroadcastReceiver,filter1);

Don’t forget to unregister the receiver if not needed.

@Override
   protected void onDestroy() {
       super.onDestroy();
       if(receiver!=null)
       {
           unregisterReceiver(receiver);
       }
   }

Now in my Application, i registered two receiver’s one is local with the custom action and other is registered in AndroidManifest file with Action power connected which will trigger once the device is connected to power.

Now Full Code:-

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.coderzpassion.broadcastsample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".MyBroadcastReceiver">
            <intent-filter>
                <action android:name="Intent.ACTION_POWER_CONNECTED"/>
            </intent-filter>
        </receiver>

    </application>

</manifest>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    BroadcastReceiver receiver;
    IntentFilter filter;
    Button sendbroadcast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        receiver=new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Toast.makeText(context,"Broadcast Received in Activity called",Toast.LENGTH_SHORT).show();
            }
        };

        // to register local receiver
        filter = new IntentFilter();
        // specify the action to which receiver will listen
        filter.addAction("com.local.receiver");
        registerReceiver(receiver,filter);

        sendbroadcast=(Button)findViewById(R.id.sendbroadcast);
        sendbroadcast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent("com.local.receiver");
                sendBroadcast(intent);
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(receiver!=null)
        {
            unregisterReceiver(receiver);
        }
    }
}

//layout for above activity

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.coderzpassion.broadcastsample.MainActivity">

    <Button
        android:id="@+id/sendbroadcast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send BroadCast!"
        android:layout_centerInParent="true" />

</RelativeLayout>

MyBroadcastReceiver.java

public class MyBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"Broadcast Received Device is connected to Power",Toast.LENGTH_SHORT).show();
    }
}

Final Results

broadcastreceiver   broadcastreceived