Friday 2 July 2021

Android app development: Implementing a broadcast receiver

Android broadcast message system works in a publish-subscribe manner. A broadcast message is sent when there is something to announce. For example, if the system wanted to announce an event such as the boot-up process completed or an incoming SMS, all the apps subscribed to such events will be notified. It is also possible for an app to send a custom broadcast to another app to communicate with it. The Android system broadcasts are often sent wrapped in Intents. So, we need to implement an Intent filter to receive an Intent of interest. This article will show you how to implement a simple broadcast receiver and perform some action based on the result. 

From your MainActivity, register the receiver as shown below.

public class MainActivity extends AppCompatActivity {
BroadcastReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
configReceiver();
}

The configReceiver() will have our code to filter the Intent and register the receiver. As an example, I will make an intent filter that will listen for a broadcast when the system detects a power disconnection.

private void configReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.ACTION_POWER_DISCONNECTED");
receiver = new MyReceiver();
registerReceiver(receiver, filter);
}

Now lets see the broadcast receiver class. You need to extend the Android BroadcastReceiver.

public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
String message = "Power disconnected!!";

Toast.makeText(context, message,
Toast.LENGTH_LONG).show();
someaction_goes_here ..
}
}

Now, unregister upon destroy.

@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}

You need to include your Receiver in Android Manifest.

<application
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.myproject">
<receiver
android:name="com.myproject.MyReceiver"
android:enabled="true"
android:exported="true">
</receiver>

<activity android:name="com.myproject.MainActivity">
    ......remaining things go here

We will see another way of implementing the receiver in my next post. Keep subscribed.