How to listen for an intent using a Broadcast Receiver in an Activity
A step by step guide on listening for an intent, that may or may not have extras, using a Broadcast Receiver in an Activity in Kotlin and Android Studio.
This post is a part of a mini series on sending and receiving functional intents in an Android app. The rest of the tutorials are available at the end.
Please note that we have chosen to use the term "Notifications" to standardize naming conventions across iOS and Android. If you wish to exchange Notifications for Intents, we welcome you too.
This particular posts demonstrates how to listen for a language content update notification. This tutorial can be found in the main branch of our Open Source repository
Step One: Setup the Notifications Coordinator
For intents to be registered across an app it must be sent from a central manager, which we call a NotificationsCoordinator.
Step Two: Broadcast the Intent
Follow the tutorial below to learn how to structure a project to manage and broadcast intents.
Step Three: Declare the Broadcast Receiver
At the top of your MainActivity.kt declare your broadcast receiver using code similar to that below.
The example of the reciever below routes the intents to functions declared in the next step.
Step Four: Create the Notifications Extension
Create a new file called MainActivity+Notifications.kt and paste in the code below.
This is where you will declare:
- What Intents your receiver will listen for, whether they are internal or external.
- All the functionality to respond to intents being received.
Please note that this functionality should be called from the receiver declared in previous step.
Step Five: Setup Notifications
In the MainActivity.kt onCreate function, call setupNotifications() to make sure that the broadcast receiver is registered.
setupNotifications()
Step Five: Unregister the Receiver
In the onDestroy lifecycle function of the MainActivity, unregister the broadcast receiver using the code below.
unregisterReceiver(broadcastReceiver)
Step Six: Test
Run the app in Android Studio and confirm that the notification is sent and received.
Looking to learn more about Intents in Android ?
Consult the tutorials linked below to learn more about sending and receiving Intents in Android and Kotlin.