Android BroadcastReceiver and Receive system Broadcast example in Kotlin

Android BroadcastReceiver is the main component of android application development. It’s work similar Publish-Subscriber design pattern. For an example action.AIRPLNE_MODEaction.BATTERY_LOW, this is some system called broadcasts.

We can create on own Broadcast for internal components call in the application or another application. The broadcast is sent when an event occurs and receivers will receive event and do some action.

Android BroadcastReceiver and Receive system Broadcast example Kotlin

How to receiving Broadcast

Apps can receive and android BroadcastReceiver in two ways: through manifest-declared receivers and context-registered receivers. In this example, we are approaching manifest-declared Receiver. Learn step by step to the kotlin broadcast receiver example works.

Step 1. Create an android app, For creating an Android app with kotlin read this tutorial.
Step 2. Creating Broadcast Receiver

Create and extend Subclass andBroadcastReceiver implement.onReceive(Context, Intent) where onReceive method each message is received as an Intent object parameter.

Step 3. Declare a broadcast receiver in the manifest file

add the element<receiver> in your app’s manifest. Here is code snap

Note: If the app is not running and broadcast receiver declared in AndroidManifest.xml, then the system will launch your app.

Step 4. MainActivity code, no needs to do anything

Step 5. Add following code in main_activity.xml

add <ImageView> and <TextView>widget layout file.

Step 6. Run the app On emulator or in android phone

 

Android Broadcast receiver

 

Download Android BroadcastReceiver source code

[wpdm_package id=’359′]

Note : This example (Project) is developed in Android Studio 3.0.1 ,tested on Android 7.1.1 ( Android Nougat), build-tools version  26.0.1

MinSdkVersion=”15″

TargetSdkVersion=”26″

Coding in Kotlin

 

Some More Uses of Android BroadcastReceiver :

  • Receiving message for OTP verification

Advantage/Benefits :

  • A Broadcast receiver wakes your application up, the inline code works only when your application is running.

Example 1: if you want your application to be notified of an incoming call, even if your app is not running, you use a broadcast receiver.

Example 2: When new SMS arrives, the broadcast receiver sends a notification to the messaging app and a small icon pops up in the notification bar.

Note: Rules of broadcast receiver: it has a maximum limit of 10secs (5-10secs), do not do any asynchronous operations which may take more time, don’t do any heavy database operations or networking operations in the broadcast receiver. Otherwise, the app will be crash (ANR-“Application Not Responding”).


One thought on “Android BroadcastReceiver and Receive system Broadcast example in Kotlin

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.