0% found this document useful (0 votes)
6 views40 pages

MAD Chapter Five

Chapter Five covers services and broadcast receivers in Android, detailing the types of services (foreground, background, and bound) and their lifecycle methods. It explains the role of broadcast receivers in responding to system events and inter-app communication, along with their registration methods. Additionally, the chapter discusses notifications, their components, types, and how to create them using NotificationCompat.Builder and NotificationManagerCompat.

Uploaded by

Hermela gg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views40 pages

MAD Chapter Five

Chapter Five covers services and broadcast receivers in Android, detailing the types of services (foreground, background, and bound) and their lifecycle methods. It explains the role of broadcast receivers in responding to system events and inter-app communication, along with their registration methods. Additionally, the chapter discusses notifications, their components, types, and how to create them using NotificationCompat.Builder and NotificationManagerCompat.

Uploaded by

Hermela gg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Chapter Five

Services and Broadcast


receivers
Content
Services
• Services
• Types of Services
• Service Lifecycle
Broadcast receivers
• Broadcast Receiver
• System Broadcasts
• Creating and Receiving
Notification
• Notification anatomy, action, appearance on devices.
• creating and displaying notification, Alarm and alarm manager
Service
▪ A service is a general-purpose entry point for keeping an
app running in the background for all kinds of reasons.
▪ A service is an application in Android that runs in the
background without needing to interact with the user.
▪ A service is a component that runs in the background to
perform long-running operations without needing to
interact with the user.
▪ A service does not provide a user interface.
Service
▪ The primary purpose of service are used for operations
that need to be executed even when the user is not
interacting with the application.
▪ Some common uses for a Service include:
▪ Downloading or uploading data from/to a network in the
background even if the app is closed
▪ Saving data to a database without crashing if the user leaves the
app
▪ Running some other kind of long-running, “background” task
even after the app is closed, such as playing music!
Service
▪ Importance of services:
▪ Services allow apps to maintain functionality even when the user
switches to another app or the device enters sleep mode.
▪ Services enable multitasking by offloading long-running
operations from the main thread, ensuring a responsive user
interface.
▪ Services are tightly integrated with Android’s system processes,
ensuring smooth execution of tasks like notifications, alarms, and
updates.
▪ Foreground services keep critical tasks running with user
awareness through persistent notifications.
Types of Service

Foreground Service

Types of Background Service


service
Bound Service
Types of Service
Foreground Service:
• These services perform tasks that are noticeable to the
user.
• They must display a notification in the status bar to keep
the user informed about its ongoing activity.
• This notification cannot be dismissed unless the service
is either stopped or removed from the foreground.
Types of Service
Background Service:
• A background service performs an operation that isn't
directly noticed by the user.
• A background service runs without user interaction or a
persistent notification.
• For example:
• Cleanup operations.
• data syncing: An app syncing data with the server periodically.
Types of Service
Bound Service:
• A bound service allows other application components
(e.g., Activities, Fragments) to bind to it and interact
directly.
• It provides a client-server interface for two-way
communication.
• A service that provides real-time updates to an activity.
• For example:
• A weather app uses a bound service to fetch real-time weather
data from a server.
• The Activity binds to the service and retrieves the current
temperature, humidity, and forecast..
Life Cycles of Service
onCreate():
• This method is called automatically by the activity manager
after the service gets started.
• Used for one-time initialization tasks such as setting up
resources, initializing variables, or starting background
threads.
@Override
public void onCreate()
{
super.onCreate(); // Initialize resources
Log.d("Service", "Service created");
}
Life Cycles of Service
onStartCommand():
• This method is a lifecycle callback in Android services,
invoked whenever the service is started using the
startService(Intent) method.
• To execute the task requested by the Intent.
• The return value of onStartCommand() determines how the
system handles the service if it is terminated due to resource
constraints:
• START_NOT_STICKY - The service will not restart automatically.
Suitable for tasks that don't need to resume if interrupted.
• START_STICKY - The service will restart automatically after being
killed, but the Intent will not be redelivered.
• START_REDELIVER_INTENT - The service will restart
automatically, and the last Intent will be redelivered.
Life Cycles of Service
onBind():
• Bound service is initiated by a client, like an activity, by
calling bind service and as a result the service gets
started, if it is not already running.
• onBind() Returns an IBinder object that allows clients to
bind to the service and interact with it directly.
• Used in Bound Services for client-server communication.
Life Cycles of Service
onUnBind():
• The system calls this method when all clients have
disconnected from a particular interface published by
the service.
• This method is used to handle the intent object, and it
unbinds the clients. This method can call onRebind()
when a new client is connected with the service.
Life Cycles of Service
onDestroy():
• Called when the service is no longer in use and is being
destroyed.
• Used for cleanup tasks such as releasing resources,
stopping threads, or closing connections.
@Override
public void onDestroy()
{
super.onDestroy(); // Cleanup resources
Log.d("Service", "Service destroyed");
}
How to create startService()?
• When startService() is called, the service is started, and it
runs in the background until it stops itself using stopSelf() or
is explicitly stopped by another component using
stopService().
• If the service is stopped, it is destroyed, and onDestroy() is
called.
Step 1: create a service
• First, you need to create a Service class.
• onCreate(): Initializes the service when it's created.
• onStartCommand(): Handles the logic for when the service is started.
• onDestroy(): Cleans up the service when it is destroyed.
• onBind(): Not used in this case since it's a started service, not a bound
service.
How to create startService()?
Step 2: Register the Service in AndroidManifest.xml
• In your AndroidManifest.xml, you need to declare the
service.
• This registers the service so that it can be started from
your activity or any other component.

<application ... >


<service android:name=".MyService" />
</application>
How to create startService()?
Step 3: Start the Service from an Activity
• Now, its possible to start the service using startService() from
your activity.
• For example, you might start the service when a button is
clicked
Button startServiceButton = findViewById(R.id.startServiceButton);
startServiceButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Start the service
Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
}
});
How to create startService()?
Step 4: Stopping the Service
• To stop the service manually, you can call stopService()
or use stopSelf() within the service.

Intent intent = new Intent(MainActivity.this, MyService.class);


stopService(intent); // Stops the service
Broadcast Receiver
• Broadcast Receiver is one of the component in Android
that enable apps to listen for and respond to broadcast
messages from other apps or the system itself.
• A Broadcast Receiver in Android is a component that
listens for and responds to broadcast messages sent by
the system or other applications.
• Broadcasts are sent when specific events occur, such as:
• when the device is charging
• when Wi-Fi is turned on or off
• when an SMS message is received.
• Broadcast receivers allow an app to react to these events
even when the app is not running in the foreground.
Broadcast Receiver
• Broadcast Receiver is one of the component in Android
that enable apps to listen for and respond to broadcast
messages from other apps or the system itself.
Broadcast Receiver
• Importance of broadcast receiver:
• React to System Events. For Example, Automatically sync data
when the device connects to Wi-Fi.
• Facilitate Inter-App Communication. For example, A
file-sharing app could notify other apps when a file download is
complete.
• Enable Event-Driven Programming. For Example, A
messaging app listens for incoming messages and displays
notifications only when a message arrives.
• Applications can define and send their own broadcasts to
communicate within or between apps.
Types of Broadcast Receiver
• In Android, broadcasts are categorized into two main
types based on their behavior and scope.

Normal Ordered
Broadcasts Broadcasts
Types of Broadcast Receiver
Ordered Broadcast:
• Ordered Broadcasts are synchronous broadcasts, and are
done in proper order.
• This order is decided by the android: priority attribute.
• The broadcast with the highest priority would execute
first and broadcasts with the same priority would not
follow any order.
• In this, one broadcast is delivered only to one receiver at
a time. When a receiver receives a broadcast it’s up to the
receiver to pass or abort the broadcast.
Types of Broadcast Receiver
Normal Broadcast:
• Normal broadcasts are asynchronous.
• This means all registered broadcast receivers receive the
broadcast at the same time, without any specific order.
• They are not interruptible, so receivers cannot stop the
broadcast or modify the content.
Broadcast Receiver Registration
Static Registration (manifest-declared):
• This receiver can be registered via the
AndroidManifest.xml file.
• This method is primarily used for system-wide broadcasts
or events that occur even when the app is not running.
• The receiver is always active as long as the app is installed.
It listens for broadcasts even when the app is not running
(e.g., boot completion).
Broadcast Receiver Registration
Dynamic Registration:
• Dynamic registration involves registering the Broadcast Receiver
programmatically at runtime.
• This method is used when you want the receiver to listen for
broadcasts only while the app or a specific component (like an
activity) is running.
• Receiver is active only when registered, typically during an activity or
service lifecycle.
• Must be explicitly unregistered to avoid memory leaks.
• Suitable for app-specific events like button clicks or temporary actions.
• Dynamic Registration is useful when you want the receiver to be
active only when your app is running, providing more control
over when it listens for broadcasts.
Broadcast Receiver Registration
Dynamic Registration:
• Dynamic registration involves registering the Broadcast Receiver
programmatically at runtime.
• This method is used when you want the receiver to listen for
broadcasts only while the app or a specific component (like an
activity) is running.
• Receiver is active only when registered, typically during an activity or
service lifecycle.
• Must be explicitly unregistered to avoid memory leaks.
• Suitable for app-specific events like button clicks or temporary actions.
• Dynamic Registration is useful when you want the receiver to be
active only when your app is running, providing more control
over when it listens for broadcasts.
How Broadcast Receiver Works?
Create a BroadcastReceiver:
• You must extend the BroadcastReceiver class and override
the onReceive() method to define what should happen
when a broadcast is received.
public class MyBroadcastReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
// Handle the broadcast
Log.d("Receiver", "Broadcast received!");
}
}
How Broadcast Receiver Works?
Register the Receiver:
• You can register a BroadcastReceiver in two ways: statical
(via AndroidManifest.xml) or dynamically (via
registerReceiver() in code).
Static Registration
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.MY_BROADCAST" />
</intent-filter>
</receiver>
Dynamic Registration
IntentFilter filter = new IntentFilter("com.example.MY_BROADCAST");
registerReceiver(myReceiver, filter);
Notification

• A notification is a message displayed outside your app's UI


to provide updates, reminders, or actions to the user.
• Notifications can appear in the status bar, on the lock
screen, or as heads-up alerts.
• Keep users updated about events or changes, even when the app
is not running in the foreground.
• Encourage users to return to the app by providing timely and
relevant information.
• Offer quick access to app features or actions.
• Provide real-time updates or alerts for critical events.
Components of Notification
Components of Notification
Title: A summarizing headline that summarizes the purpose
of the notification.
Content Text: A brief message that provides additional
details about the notification.
Small Icon: A small image displayed in the status bar and
notification drawer.
Actions: Buttons that allow users to take immediate actions
directly from the notification.
Types of Notification
User Generated:
• Notifications created directly by the user's actions or inputs
within the application.
• User activity or interaction with the app and these are local
to the device.
• Does not require external data or server communication.
• Provides feedback or reminders for user-initiated tasks.
• Examples:
• A reminder for a task created by the user in a to-do app.
• Notifications for a completed file upload in a file manager.
Types of Notification
System-Generated:
• Notifications triggered by the operating system or the app’s
internal logic, often without user intervention.
• It can be triggered by system events or internal app
processes based on predefined conditions.
• Enhances the app's functionality by keeping users informed
of important events.
• Examples:
• Low battery alerts.
• Background app updates completed.
Types of Notification
Context-Based:
• Notifications generated based on real-time contextual
information like location, time, or activity.
• It can be triggered by device sensors, location data, or
predefined conditions in the app logic.
• Enhances user engagement by delivering Personalized and
dynamic relevant information at the right time.
• Examples:
• Location-based offers in a shopping app.
• A notification about weather conditions when the user enters a
new city.
Types of Notification
Push Notifications:
• Notifications sent from a remote server to the user's device
using a push service (e.g., Firebase Cloud Messaging).
• It might be triggered by External server events or updates.
• Allows real-time updates from the server to the user’s
device using internet connectivity.
• Widely used for marketing, updates, or critical alerts.
• Examples: A messaging app notifying about a new
message.
How to Create Notification
NotificationCompat.Builder :
• is a class in the Android Support Library (now part of
AndroidX) that helps developers create and manage
notifications in Android applications.
How to Create Notification
NotificationManagerCompat:
• NotificationManagerCompat is a class in the AndroidX
library designed to simplify the process of managing
notifications in a backward-compatible way.
How to Create Notification
NotificationChannel:
• NotificationChannel is a class introduced in Android 8.0
(API level 26) that provides a mechanism for grouping and
managing notifications.
• It allows developers:
• Group similar types of notifications under a single channel.
• Users can modify settings for each channel, such as enabling or
disabling notifications, changing sound, or vibration preferences.
• Developers can define importance, sound, lights, vibration, and
other properties for each channel.
Thank you!

You might also like