Android Broadcast Receivers and Notifications
Overview
In the Android ecosystem, Broadcast Receivers and Notifications play critical roles in facilitating inter-component communication and informing users about relevant actions and events. Broadcast Receivers allow applications to receive and respond to system-wide announcements or events, even when the app is not in the foreground. Notifications, on the other hand, are user-visible messages intended to inform users about specific events, updates, or alerts from the app.
Android Broadcast Receivers
Broadcast Receivers are fundamental components in Android that respond to system-wide broadcast announcements. These messages can originate from either the Android system itself (such as boot completed, incoming SMS, low battery) or from other apps.
Types of Broadcast Receivers:
- Normal Broadcasts: Delivered to all receivers in an undefined order. They are asynchronous and cannot deliver results to any receiver.
- Ordered Broadcasts: Delivered to one receiver at a time, in priority order. Each receiver has the option to stop the propagation of the broadcast or modify it before passing it to the next receiver.
- Sticky Broadcasts: These broadcasts remain sticky after being delivered. They are not currently supported on Android 12 and higher due to security and privacy concerns.
- Foreground Service Bound Broadcast Receivers: These are bound to the lifecycle of a foreground service and are useful for long-running tasks.
Implementing Broadcast Receivers:
Registering a Broadcast Receiver:
- Manifest Declaration: The simplest way to register a receiver is to declare it in the AndroidManifest.xml file.
<receiver android:name=".MyReceiver" />
- Dynamic Registration: This involves registering the receiver at runtime using a context.
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(myReceiver, filter);
- Manifest Declaration: The simplest way to register a receiver is to declare it in the AndroidManifest.xml file.
Handling Received Broadcasts: The
onReceive()
method is invoked whenever a broadcast with a matching intent is sent.public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // Handle the broadcast } }
Permission Control: Broadcasts can be protected using permission tags, both for sending (
sendBroadcast(Intent, String)
) and receiving (<receiver android:permission>
).
Android Notifications
Notifications are a cornerstone of Android UI design, providing users with timely and relevant information without disturbing their current activity. They can be used to inform users of new messages, notifications from social media apps, calendar reminders, and more.
Components of a Notification:
- Status Bar Icon: The icon that appears in the status bar to represent the notification.
- Ticker Text: The initial text displayed when the notification is posted.
- Content Title: The title of the notification, usually a short summary.
- Content Text: A more detailed text describing the notification.
- Actions: Buttons or actions the user can take from the notification itself.
- Content Intent: An Intent that starts an activity when the user taps on the notification.
Creating Notifications:
- NotificationManager: This service is responsible for showing and managing notifications.
- NotificationCompat.Builder: This class assists in constructing notifications for compatibility with older Android versions.
Steps to Create a Notification:
Initialize the NotificationManager:
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Create a Notification Channel (API 26 and above):
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel( CHANNEL_ID, "Channel Name", NotificationManager.IMPORTANCE_DEFAULT ); notificationManager.createNotificationChannel(channel); }
Build the Notification:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification) .setContentTitle("New Message") .setContentText("You've received a message!") .setPriority(NotificationCompat.PRIORITY_DEFAULT);
Define the Content Intent:
Intent resultIntent = new Intent(this, MainActivity.class); PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(resultPendingIntent);
Display the Notification:
notificationManager.notify(NOTIFICATION_ID, builder.build());
Best Practices for Notifications:
- Clarity: Ensure your notifications are clear, concise, and informative.
- Relevance: Only send notifications that are relevant and useful to the user.
- Opt-Out: Provide an option for users to opt-out of non-essential notifications.
- Response Action: Allow users to respond to notifications directly from the notification shade.
Conclusion
Broadcast Receivers and Notifications are integral to building robust, user-friendly Android applications. Broadcast Receivers enable apps to respond to system-wide events, enhancing their interaction with the Android environment and other applications. Notifications, in turn, help keep users informed about timely and relevant updates without disrupting their current activities. By understanding and effectively utilizing these components, developers can create a more engaging and responsive user experience.
This overview covers the essential concepts, implementation details, and best practices for using Broadcast Receivers and Notifications in Android applications. Proper use of these features can significantly enhance the overall functionality and user experience of your app.
Android Broadcast Receivers and Notifications: Examples, Set Route, and Run Application Then Data Flow (Step-by-Step Guide for Beginners)
Introduction
Broadcast receivers are a fundamental component of Android applications that allow you to listen for and respond to system-wide broadcast announcements. For example, they can receive notifications when the battery is low, an SMS message is received, or the device connects to a Wi-Fi network. In parallel, notifications are a way to inform users about events that happen in your app, even when it’s not actively running.
This guide will provide a detailed, step-by-step explanation on how to create Android applications using broadcast receivers and send notifications to the user. We'll start with setting your development environment, creating the necessary routes, running the application, and then dive into understanding the data flow within the application.
Prerequisites
- Android Studio: Make sure you have the latest version installed.
- Basic Knowledge: Familiarity with Java/Kotlin and Android basics.
- Device/Emulator: An Android device or an emulator to test the app.
Setting Up Your Development Environment
First, let's start by creating a new project.
- Open Android Studio.
- Click on
Start a new Android Studio project
. - Choose
Empty Activity
and clickNext
. - Name your application (e.g.,
BroadcastReceiverAndNotification
) and select Kotlin or Java as your language. - Set the minimum API level (at least 21 for compatibility) and click
Finish
.
Implementing a Broadcast Receiver
Step 1: Define the Broadcast Receiver
Broadcast receivers are defined either in the app's manifest file or programmatically. Here we will define it in the manifest.
Create a new Kotlin class (or Java if chosen earlier), e.g., MyBatteryLowBroadcastReceiver.kt
.
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.core.app.NotificationCompat
class MyBatteryLowBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (Intent.ACTION_BATTERY_LOW == intent?.action) {
// Create and show the notification here
val builder = NotificationCompat.Builder(context!!, "channel_id")
.setSmallIcon(R.drawable.ic_battery_alert)
.setContentTitle("Battery Low")
.setContentText("Your battery is below 15%")
.setPriority(NotificationCompat.PRIORITY_HIGH)
// Get the System service NotificationManager
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
// Notify the user
notificationManager.notify(1, builder.build())
}
}
}
Step 2: Register the Broadcast Receiver in Manifest
Open AndroidManifest.xml
and declare your receiver inside the <application>
tags:
<receiver android:name=".MyBatteryLowBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BATTERY_LOW" />
</intent-filter>
</receiver>
You will also need to add the notification channel (for Android Oreo and higher):
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
Step 3: Create a Notification Channel
For Android Oreo (API level 26) and above, you must create a notification channel. Add this function to your MainActivity
or any applicable activity:
fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Battery Low Channel"
val descriptionText = "Channel for low battery alerts"
val importance = NotificationManager.IMPORTANCE_HIGH
val channel = NotificationChannel("channel_id", name, importance).apply {
description = descriptionText
}
// Register the channel with the system
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
Call this method from the onCreate()
method in MainActivity
:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
createNotificationChannel()
}
Running the Application and Triggering the Data Flow
Step 1: Connect Device/Emulator
Run the application by clicking the green arrow at the top of Android Studio. Ensure your device/emulator is connected via USB or is ready to use.
Step 2: Test Battery-Low Receiver
Testing the battery low scenario directly on a physical device isn’t practical, but you can simulate it on an emulator.
- Open AVD Manager (
Tools > AVD Manager
). - Select your emulator, and click the down-arrow (
Actions
). SelectWipe Data
, thenOK
. - Start the emulator.
- Install the application.
- Return to AVD Manager, select your emulator, open the
More
tab (...
), and chooseAdvanced Settings
. - Set
Battery status
toCritical Low
or manually set battery percentage close to zero.
The app should now trigger the battery-low broadcast receiver, leading to the creation and display of a notification.
Data Flow Explanation
Here is a simplified breakdown of how everything flows:
Battery-Low Event: When your device’s battery level reaches a critical threshold, Android broadcasts a system-wide event with the action
ACTION_BATTERY_LOW
.Broadcast Receiver Registration: The broadcast receiver is registered in the app’s manifest with an
<intent-filter>
indicating that it listens forACTION_BATTERY_LOW
.Receiving the Broadcast:
- When the broadcast occurs, Android looks for any registered receivers that can handle the event.
- If your app has a receiver registered for this action, Android calls the receiver's
onReceive()
method passing in the context and intent.
Creating the Notification:
- Inside the
onReceive()
method, you check if the received action matchesACTION_BATTERY_LOW
. - If matched, you prepare and build a notification (using
NotificationCompat.Builder
).
- Inside the
Displaying the Notification:
- You retrieve the
NotificationManager
system service from the context and call itsnotify()
method while passing in a unique ID (1
in this case) and the freshly created notification.
- You retrieve the
Conclusion
Understanding and implementing Android Broadcast Receivers along with sending notifications can enhance the responsiveness and functionality of your apps even when they're not actively being used. This guide provides a practical example of handling ACTION_BATTERY_LOW
events and displaying corresponding notifications. While testing, you encountered the use of a simulated event in an Android emulator, which illustrates how you can debug these features without affecting your real device.
Feel free to explore more about different types of Broadcast Receivers (like dynamic receivers registered programmatically), advanced notification features (with actions), and permissions needed for certain types of broadcasts. Happy coding!