Android Broadcast Receivers And Notifications Complete Guide
Understanding the Core Concepts of Android Broadcast Receivers and Notifications
Android Broadcast Receivers and Notifications
Broadcast Receivers: Broadcast receivers are the entry point for apps to receive messages from any source, whether within or outside the application. There are two types of broadcasts: Normal and Ordered. Normal broadcasts are delivered to all recipients at the same time, while ordered broadcasts are sent to one recipient at a time based on their priority.
Key Components and Details:
- Intent Filters: Broadcast receivers can subscribe to intents in the manifest file or register dynamically within an app. Intent filters specify the type of broadcast the receiver is interested in.
- Manifest Declaration: To define a receiver, you declare it in the app's
AndroidManifest.xml
file and use intent filters to specify what types of broadcasts it should handle. - Lifecycle: BroadcastReceiver executes in its own background thread, but if launched from within an Activity context, it will run on the UI thread. Hence, long operations are discouraged.
- Security Considerations: Apps can secure intents using permissions to restrict who can send or receive them.
- LocalBroadcastManager: This allows sending and receiving broadcasts within the same app, which is more efficient than global broadcasts.
- System Events: Broadcast receivers can listen to various system-generated events like battery low, device boot-up, and network status changes.
- Custom Broadcasts: Developers can create custom broadcasts to communicate between different components of their app.
Example Usage:
Suppose you want your app to perform some task when the device boots up, such as scheduling recurring alarms. You would create a BroadcastReceiver that listens for the BOOT_COMPLETED
action and perform necessary actions.
<receiver android:name=".BootCompletedReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
And in BroadcastReceiver class:
public class BootCompletedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
// Schedule alarms here
}
}
}
Notifications: Notifications are messages displayed outside your app's UI to alert the user about an event. They provide quick actions without opening the app, making them essential for user engagement and information delivery.
Key Components and Details:
- NotificationManager: Central point for displaying and managing notifications within an app.
- NotificationChannel (API 26+): Introduced in Android Oreo (8.0), channels categorize notifications and let users adjust notification settings for each channel.
- Builder Pattern: For constructing notifications, Android uses the Builder pattern, allowing you to build complex notifications step-by-step.
- PendingIntent: Used for adding an action to a notification, such as launching an Activity or executing a BroadcastReceiver when the user interacts with the notification.
- Notification Styles: Android provides various styles, including BigTextStyle for longer text, InboxStyle for multiple lines of text, and MessagingStyle for notifications with multiple messages.
- Custom Layouts: Notifications can also have custom layouts designed using XML, offering a more personalized experience.
- Priority: Different priorities affect the behavior of notifications, such as how loud they are and where they appear on the screen.
- Actions: Notifications can include actions, enabling users to take action directly from the notification shade without needing to open the app.
- Foreground Service: Apps performing ongoing, long-running operations often use foreground services with persistent notifications to inform the user.
Example Usage: To send a simple notification:
Online Code run
Step-by-Step Guide: How to Implement Android Broadcast Receivers and Notifications
What are Android Broadcast Receivers?
Broadcast Receivers allow you to listen to and respond to system-wide broadcast announcements, such as changes in network connectivity, battery status, or even custom events broadcast within your app.
What are Notifications?
Notifications are messages that appear on the lock screen or within the notification shade, informing the user about events happening in your app or other apps.
Example: Creating a Simple App to Handle Broadcast and Show Notifications
Let's create a simple Android application that listens for a custom broadcast and shows a notification whenever that broadcast is received.
Step 1: Set Up Your Android Project
- Create a new Android Project in Android Studio.
- Open Android Studio.
- Click "Start a new Android Studio project".
- Choose "Empty Activity" and click "Next".
- Name your application (e.g.,
BroadcastReceiverAndNotificationApp
). - Choose a package name.
- Set the Minimum SDK to API level 21 or above (Lollipop).
- Click "Finish" to create the project.
Step 2: Define the Broadcast Receiver
Create a BroadcastReceiver to listen for a custom broadcast event.
- Create a new Java class named
MyBroadcastReceiver
and extendBroadcastReceiver
.
// MyBroadcastReceiver.java
package com.example.broadcastreceiverandnotificationapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
public class MyBroadcastReceiver extends BroadcastReceiver {
private static final String CHANNEL_ID = "example_channel_id";
@Override
public void onReceive(Context context, Intent intent) {
// Handle the broadcast intent here
String action = intent.getAction();
if (action != null && action.equals("com.example.CUSTOM_ACTION")) {
// Show a notification
showNotification(context);
}
}
private void showNotification(Context context) {
// Build the notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Broadcast Received")
.setContentText("You have received a custom broadcast!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
// Get the NotificationManager
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
// Notify the user
notificationManager.notify(1, builder.build());
}
}
- Add an Icon for the Notification.
- Add a PNG icon named
ic_notification.png
to theres/drawable
folder.
- Add a PNG icon named
Step 3: Register the BroadcastReceiver
You can register a BroadcastReceiver dynamically in code or statically in the AndroidManifest.xml
.
Option 1: Register BroadcastReceiver Statically
- Register the BroadcastReceiver in
AndroidManifest.xml
.
<!-- AndroidManifest.xml -->
<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/Theme.BroadcastReceiverAndNotificationApp">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Register the BroadcastReceiver -->
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.CUSTOM_ACTION" />
</intent-filter>
</receiver>
</application>
Option 2: Register BroadcastReceiver Dynamically (Optional)
- Register the BroadcastReceiver in
MainActivity.java
at runtime.
// MainActivity.java
package com.example.broadcastreceiverandnotificationapp;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private MyBroadcastReceiver broadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create an instance of the BroadcastReceiver
broadcastReceiver = new MyBroadcastReceiver();
// Register the BroadcastReceiver
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.CUSTOM_ACTION");
registerReceiver(broadcastReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
// Unregister the BroadcastReceiver
unregisterReceiver(broadcastReceiver);
}
}
Step 4: Create a Notification Channel
For Android Oreo (API level 26) and above, you must create a Notification Channel.
- Create a method to create the notification channel.
// MainActivity.java
import androidx.core.app.NotificationChannelCompat;
import androidx.core.app.NotificationManagerCompat;
public class MainActivity extends AppCompatActivity {
private static final String CHANNEL_ID = "example_channel_id";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the notification channel
createNotificationChannel();
// ... (Rest of the code)
}
private void createNotificationChannel() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
CharSequence name = "Example Channel";
String description = "This is an example notification channel";
int importance = NotificationManagerCompat.IMPORTANCE_DEFAULT;
NotificationChannelCompat channel = new NotificationChannelCompat.Builder(CHANNEL_ID, importance)
.setName(name)
.setDescription(description)
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.createNotificationChannel(channel);
}
}
// ... (Rest of the code)
}
Step 5: Send the Custom Broadcast
You can send the custom broadcast from within your app to test the functionality.
- Add a Button to the Main Activity layout to send the broadcast.
<!-- res/layout/activity_main.xml -->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/sendBroadcastButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Broadcast"
android:layout_centerInParent="true" />
</RelativeLayout>
- Add a click listener to send the broadcast when the button is clicked.
// MainActivity.java
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
// ... (Previous code)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the notification channel
createNotificationChannel();
// Register the BroadcastReceiver
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.CUSTOM_ACTION");
registerReceiver(broadcastReceiver, intentFilter);
// Send broadcast button
Button sendBroadcastButton = findViewById(R.id.sendBroadcastButton);
sendBroadcastButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendCustomBroadcast();
}
});
}
private void sendCustomBroadcast() {
Intent intent = new Intent("com.example.CUSTOM_ACTION");
sendBroadcast(intent);
}
// ... (Rest of the code)
}
Step 6: Test Your Application
- Run the app on an emulator or a physical device.
- Click the "Send Broadcast" button.
- Check the notification shade to see the notification.
Summary
In this example, we created a BroadcastReceiver to listen for a custom broadcast action. When the broadcast is received, the app shows a notification. We registered the BroadcastReceiver in the AndroidManifest.xml
and created a notification channel for devices running Android Oreo and above.
Top 10 Interview Questions & Answers on Android Broadcast Receivers and Notifications
1. What is a Broadcast Receiver in Android?
A Broadcast Receiver is an Android component that responds to system-wide broadcast announcements (known as Intents). These broadcasts can come from the system itself or from another application. Broadcast Receivers are useful for performing actions in response to these events, such as receiving SMS messages, charging the phone, or changes in network connectivity.
2. Types of Broadcasts in Android?
There are two main types of broadcasts in Android:
- Normal Broadcasts: Sent to all receivers at the same time and are non-sequential. There is no concept of priority, and none of the receivers can abort the message or change its result.
- Ordered Broadcasts: Sent to one receiver at a time based on their declared priority. A higher priority number indicates a higher priority. If a receiver processes the broadcast, it can propagate the result to the next one using
setResultCode()
andsetResultData()
, and even abort the broadcast by callingabortBroadcast()
.
3. How do you declare a BroadcastReceiver in the AndroidManifest.xml?
To declare a BroadcastReceiver in the AndroidManifest.xml, use the <receiver>
tag within the <application>
element. Here’s an example of declaring a normal broadcast receiver:
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
If your broadcast receiver is dynamic (registered in runtime), you don’t need to declare it in the manifest.
4. How do you create a BroadcastReceiver in code?
To create a BroadcastReceiver in Java or Kotlin, extend the BroadcastReceiver
class and override the onReceive()
method. Here’s how you do it in both Java and Kotlin:
Java:
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Handle the broadcast
}
}
Kotlin:
class MyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
// Handle the broadcast
}
}
5. Can a BroadcastReceiver start an Activity or Service?
BroadcastReceivers have a limited lifecycle and should perform quick actions. Typically, they are used to start a service or send a notification instead of starting an activity directly, especially if the broadcast was sent with a low-priority signal. However, you can technically start a foreground activity from a broadcast, but it's not a recommended practice due to user experience considerations and system policies, like background restriction introduced in Android Oreo (Version 8).
6. What is a Notification in Android?
Notifications are messages that appear outside your application’s UI to inform the user about specific events or updates. They usually appear in the status bar and provide information about what happened, and possibly some actions the user can take. Starting from Android Oreo, notifications must be associated with a notification channel.
7. What are the different parts of a Notification?
- Icon: Small icon representing your application.
- App Name: The name of the app that posted the notification.
- Title: Brief title to summarize the notification.
- Text: More detailed body text describing the event.
- Timestamp: When the notification was posted.
- Actions: Buttons that allow users to interact with the notification without opening the app.
- Channel: On Android Oreo and above, notifications belong to channels, which define the behavior and importance of the notifications.
8. How do you create and display a Notification in Android?
First, you need to create a NotificationChannel
if targeting Android Oreo or higher, then use the NotificationManager
for displaying the notification.
Here’s how you can create and show a simple notification in Java and Kotlin:
Java:
NotificationChannel channel = new NotificationChannel("channel_id", "channel_name", NotificationManager.IMPORTANCE_DEFAULT);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MyClass.this,"channel_id")
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Notification Title")
.setContentText("This is the notification text")
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(1, builder.build());
Kotlin:
Login to post a comment.