Android Broadcast Receivers and Notifications Step by step Implementation and Top 10 Questions and Answers
 .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    Last Update: April 01, 2025      12 mins read      Difficulty-Level: beginner

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:

  1. Normal Broadcasts: Delivered to all receivers in an undefined order. They are asynchronous and cannot deliver results to any receiver.
  2. 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.
  3. 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.
  4. 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:

  1. 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);
      
  2. 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
        }
    }
    
  3. 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:

  1. Status Bar Icon: The icon that appears in the status bar to represent the notification.
  2. Ticker Text: The initial text displayed when the notification is posted.
  3. Content Title: The title of the notification, usually a short summary.
  4. Content Text: A more detailed text describing the notification.
  5. Actions: Buttons or actions the user can take from the notification itself.
  6. Content Intent: An Intent that starts an activity when the user taps on the notification.

Creating Notifications:

  1. NotificationManager: This service is responsible for showing and managing notifications.
  2. NotificationCompat.Builder: This class assists in constructing notifications for compatibility with older Android versions.

Steps to Create a Notification:

  1. Initialize the NotificationManager:

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
  2. 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);
    }
    
  3. 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);
    
  4. 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);
    
  5. 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

  1. Android Studio: Make sure you have the latest version installed.
  2. Basic Knowledge: Familiarity with Java/Kotlin and Android basics.
  3. 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.

  1. Open Android Studio.
  2. Click on Start a new Android Studio project.
  3. Choose Empty Activity and click Next.
  4. Name your application (e.g., BroadcastReceiverAndNotification) and select Kotlin or Java as your language.
  5. 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.

  1. Open AVD Manager (Tools > AVD Manager).
  2. Select your emulator, and click the down-arrow (Actions). Select Wipe Data, then OK.
  3. Start the emulator.
  4. Install the application.
  5. Return to AVD Manager, select your emulator, open the More tab (...), and choose Advanced Settings.
  6. Set Battery status to Critical 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:

  1. 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.

  2. Broadcast Receiver Registration: The broadcast receiver is registered in the app’s manifest with an <intent-filter> indicating that it listens for ACTION_BATTERY_LOW.

  3. 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.
  4. Creating the Notification:

    • Inside the onReceive() method, you check if the received action matches ACTION_BATTERY_LOW.
    • If matched, you prepare and build a notification (using NotificationCompat.Builder).
  5. Displaying the Notification:

    • You retrieve the NotificationManager system service from the context and call its notify() method while passing in a unique ID (1 in this case) and the freshly created notification.

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!