0% found this document useful (0 votes)
131 views28 pages

Mobile Applications Lecture 7 - Foreground and Background Services

This document discusses foreground and background services in Android. It provides examples of creating a foreground service that plays music and a notification. It also discusses starting and binding services, and using intents and intent filters to start activities, services, and deliver broadcasts between app components. The key aspects covered are how to create and manage foreground and background services, and how intents are used to facilitate communication between app components.

Uploaded by

Omar Magdy
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)
131 views28 pages

Mobile Applications Lecture 7 - Foreground and Background Services

This document discusses foreground and background services in Android. It provides examples of creating a foreground service that plays music and a notification. It also discusses starting and binding services, and using intents and intent filters to start activities, services, and deliver broadcasts between app components. The key aspects covered are how to create and manage foreground and background services, and how intents are used to facilitate communication between app components.

Uploaded by

Omar Magdy
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/ 28

DM461 Mobile Applications

Lecture 7 – Foreground
and Background
Services

Dr. Amira Sayed A. Aziz


Faculty of Computers and Information Technology
Agenda

 Foreground Services
 Background Tasks
 Intents and Intent Filters
Started Service Simple Example

o Create an activity with two buttons Start and


Start
Stop, where Start-button starts to play some
audio file as application music and Stop-button Stop
will stop that music.

o Start button ID: startbtn


o Stop button ID: stopbtn
Create Service Class
public class MusicService extends Service {
MediaPlayed mp;
public int onStartCommand(Intent intent, int flags, int startId){
mp = MediaPlayer.create(this,Settings.System.DEFAULT_RINGTONE_URI);
mp.setLooping(true);
mp.start();
return START_NOT_STICKY;
}
public void onDestroy() {
mp.stop();
return super.onDestroy();
}
public IBinder onBind(Intent intent) {
return null; //block binding
}
}
Adding listeners to buttons

//Inside Activity onCreate() method


Startbtn = findViewById(R.id.Startbtn);
Stopbtn = findViewById(R.id.Stopbtn);

Startbtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
startService(new Intent(MainActivity.this,
MusicService.class));
}});
Stopbtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
stopService(new Intent(MainActivity.this,
MusicService.class));
}});
Adding service to Manifest file

<service android:name=“.MusicService”/>
Foreground Services

 Foreground services perform operations that are noticeable to the user. A


Foreground Service is a service that stays alive even when the app is terminated.
 Foreground services show a status bar notification, to make users aware that your
app is performing a task in the foreground and is consuming system resources.
 Examples of apps that use foreground services include the following:
 A music player app that plays music in a foreground service. The notification might show
the current song being played.
 A fitness app that records a user's run in a foreground service, after receiving permission
from the user. The notification might show the distance that the user has traveled during
the current fitness session.
 Only use a foreground service when your app needs to perform a task that is
noticeable by the user, even when they're not directly interacting with the app.
Foreground Services

 Starting in Android 13 (API level 33), users can dismiss the notification
associated with a foreground service by default. To do so, users perform a
swipe gesture on the notification.
 Traditionally, the notification isn't dismissed unless the foreground service is
either stopped or removed from the foreground.
 If you want the notification non-dismissable by the user, pass true into the
setOngoing() method when you create your notification using
Notification.Builder.
Notifications

 If a foreground service has at least one of the following


characteristics, the system shows the associated notification
immediately after the service starts, even on devices that run
Android 12 or higher:
 The service is associated with a notification that includes action buttons.
 The service has a foregroundServiceType of mediaPlayback,
mediaProjection, or phoneCall.
 The service provides a use case related to phone calls, navigation, or
media playback, as defined in the notification's category attribute.
 The service has opted out of the behavior change by passing
FOREGROUND_SERVICE_IMMEDIATE into setForegroundServiceBehavior()
when setting up the notification.
Notifications

 Apps that target Android 9 (API level 28) or higher and use foreground services need
to request the FOREGROUND_SERVICE permission, as shown in the following code
snippet.
 This is a normal permission, so the system automatically grants it to the requesting
app.

<manifest xmlns:android="http://schemas.android.com/apk/res/android" ...>

<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

<application ...>
...
</application>
</manifest>
Starting a Foreground Service

 Before you request the system to run a service as a foreground service, start
the service itself.

Context context = getApplicationContext( );


Intent intent = new Intent(...); // Build the intent for the service
context.startForegroundService(intent);

 Inside the service, usually in onStartCommand(), you can request that your
service run in the foreground. To do so, call startForeground().
 This method takes two parameters: a positive integer that uniquely identifies
the notification in the status bar and the Notification object itself.
Starting a Foreground Service

Notification notification =
new Notification.Builder(this, CHANNEL_DEFAULT_IMPORTANCE)
.setContentTitle(getText(R.string.notification_title))
.setContentText(getText(R.string.notification_message))
.setSmallIcon(R.drawable.icon)
.setContentIntent(intent)
.setTicker(getText(R.string.ticker_text))
.build();

// Notification ID cannot be 0.
startForeground(ONGOING_NOTIFICATION_ID, notification);
Background Service

 A Background Service is a service that runs only when the app is running so
it’ll get terminated when the app is terminated.
 To create a Background Service
(1) create a new Class and have it extend the Service class.
(2) Inside the class, override the onBind() and onStartCommand() methods.
(3) Add service to manifest file.
(4) Start the service.
Background Service
Background Service
Bound Service

 A bound service is the server in a client-server interface. It lets components


such as activities bind to the service, send requests, receive responses, and
perform interprocess communication (IPC).
 A bound service typically lives only while it serves another application
component and does not run in the background indefinitely.
 A bound service is an implementation of the Service class that lets other
applications bind to it and interact with it. To provide binding for a service,
you implement the onBind() callback method.
 This method returns an IBinder object that defines the programming interface
that clients can use to interact with the service.
Bound Service

 There are three ways of creating bound services:


1. First is by extending the binder class
2. Second is by using a messenger
3. Third, is by using AIDL or Android Interface Definition Language.
Extend Binder Class

 If your service is private to your own application and runs in the same
process as the client, which is common, create your interface by extending
the Binder class and returning an instance of it from onBind().
 The client receives the Binder and can use it to directly access public
methods available in either the Binder implementation or the Service.
 This is the preferred technique when your service is merely a background
worker for your own application.
 The only use case when this is not the preferred way to create your
interface is if your service is used by other applications or across separate
processes.
Extend Binder Class

1. In your service, create an instance of Binder that does one of the


following:
 Contains public methods that the client can call.
 Returns the current Service instance, which has public methods the
client can call.
 Returns an instance of another class hosted by the service with public
methods the client can call.
2. Return this instance of Binder from the onBind() callback method.
3. In the client, receive the Binder from the onServiceConnected()
callback method and make calls to the bound service using the
methods provided.
Intents and Intent Filters

 An Intent is a messaging object you can use to request an action from


another app component.
 Although intents facilitate communication between components in several
ways, there are three fundamental use cases:
 Starting an activity.
 Starting a service.
 Delivering a broadcast.
Starting an Activity

 You can start a new instance of an Activity by passing an Intent to


startActivity(). The Intent describes the activity to start and carries any
necessary data.
 If you want to receive a result from the activity when it finishes, call
startActivityForResult().
 Your activity receives the result as a separate Intent object in your activity's
onActivityResult() callback.
Starting a Service

 With Android 5.0 (API level 21) and later, you can start a service with
JobScheduler.
 For versions earlier than Android 5.0 (API level 21), you can start a service by
using methods of the Service class.
 You can start a service to perform a one-time operation (such as
downloading a file) by passing an Intent to startService(). The Intent
describes the service to start and carries any necessary data.
 If the service is designed with a client-server interface, you can bind to the
service from another component by passing an Intent to bindService().
Delivering a Broadcast

 A broadcast is a message that any app can receive.


 The system delivers various broadcasts for system events, such as when the
system boots up or the device starts charging.
 You can deliver a broadcast to other apps by passing an Intent to
sendBroadcast() or sendOrderedBroadcast().
Intent Types

 Explicit Intents
 specify which application will satisfy the intent, by supplying either the target
app's package name or a fully-qualified component class name.
 You'll typically use an explicit intent to start a component in your own app,
because you know the class name of the activity or service you want to start.
 For example, you might start a new activity within your app in response to a user
action, or start a service to download a file in the background.
 Implicit Intents
 do not name a specific component, but instead declare a general action to
perform, which allows a component from another app to handle it.
 For example, if you want to show the user a location on a map, you can use an
implicit intent to request that another capable app show a specified location on
a map.
Intent Types

When you use an implicit intent, the


Android system finds the appropriate
component to start by comparing the
contents of the intent to the intent filters
declared in the manifest file of other apps
on the device. If the intent matches an
intent filter, the system starts that
component and delivers it the Intent
object. If multiple intent filters are
compatible, the system displays a dialog so
the user can pick which app to use.
Intent Filter

 An intent filter is an expression in an app's manifest file that specifies the


type of intents that the component would like to receive.
 For instance, by declaring an intent filter for an activity, you make it possible
for other apps to directly start your activity with a certain kind of intent.
 Likewise, if you do not declare any intent filters for an activity, then it can be
started only with an explicit intent.
Building an Intent

 An Intent object carries information that the Android system uses to


determine which component to start, plus information that the recipient
component uses in order to properly perform the action.
 The primary information contained in an Intent is the following:
 Component name
 Action (ACTION_VIEW, ACTION_SEND)
 Data
 Category (CATEGORY_BROWSABLE, CATEGORY_LAUNCHER)
 Extras
 Flags
References

 Services overview | Android Developers


 https://medium.com/@Codeible/understanding-and-using-services-in-
android-background-foreground-services-8130f6bbf2a5
 https://developer.android.com/guide/components/bound-services
 https://developer.android.com/guide/components/intents-filters
 https://developer.android.com/guide/components/intents-common

You might also like