Skip to content

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 example action.AIRPLNE_MODEaction.BATTERY_LOW, this is some system called broadcasts.

We can create on our own Broadcast for internal components call in the application or another application. The broadcast is sent when an event occurs and receivers will receive the 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.

package `in`.eyehunt.androidbroadcasts

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast

class MyReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        Toast.makeText(context, "Broadcast : Flight mode changed.",
                Toast.LENGTH_LONG).show()
    }
}

 

Step 3. Declare a broadcast receiver in the manifest file

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

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

    <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=".MyReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.AIRPLANE_MODE"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

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
package `in`.eyehunt.androidbroadcasts

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}
Step 5. Add following code in main_activity.xml

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

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    android:background="@color/colorPrimary"
    tools:context="in.eyehunt.androidbroadcasts.MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_margin="8dp"
        android:layout_marginTop="16dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@mipmap/baseline_airplanemode_active_white_24" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="300dp"
        android:layout_height="36dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:gravity="center_vertical"
        android:text="Flight Mode"
        android:textColor="@color/colorWhite"
        android:textSize="24dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/imageView"
        app:layout_constraintTop_toTopOf="@+id/imageView" />
</android.support.constraint.ConstraintLayout>
Step 6. Run the app On emulator or in android phone
Android Broadcast receiver

Download Android BroadcastReceiver source code

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 the broadcast receiver: it has a maximum limit of 10secs (5-10secs), does 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”).

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

Leave a Reply

Your email address will not be published. Required fields are marked *