Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 22

SERVICES IN ANDROID

SERVICES
• Services in Android are a special component that facilitates an application to run in the
background in order to perform long-running operation tasks.

• The prime aim of a service is to ensure that the application remains active in the background so
that the user can operate multiple applications at the same time.

• A user-interface is not desirable for android services as it is designed to operate long-


running processes without any user intervention.

• A service can run continuously in the background even if the application is closed or the user
switches to another application

• Application components can bind itself to service to carry out inter-process


communication(IPC).
SERVICES VS. THREADS
• Thread is a feature provided by the Operating system to allow the user to perform operations in the
background.
• Service is an android component that performs a long-running operation about which the user might
not be aware of as it does not have UI.
• If you must perform work outside of the main thread, but only while the user is interacting with your
application, you should instead create a new thread in the context of another application component.
• For example, if you want to play some music, but only while your activity is running, you might
create a thread in onCreate(), start running it in onStart(), and stop it in onStop(). Also consider using
thread pools and executors from the java.util.concurrent package or Kotlin coroutines instead of the
traditional Thread class.
• Remember that if you do use a service, it still runs in your application's main thread by default, so you
should still create a new thread within the service if it performs intensive or blocking operations
TYPES OF ANDROID SERVICES
FOREGROUND SERVICES

Services that notify the user about its ongoing operations are termed as
Foreground Services.

Users can interact with the service by the notifications provided


about the ongoing task.

Such as in downloading a file, the user can keep track of the progress in downloading
and can also pause and resume the process.
BACKGROUND SERVICES

Background services do not require any user intervention.

These services do not notify the user about ongoing background


tasks and users also cannot access them.

The process like schedule syncing of data or storing of data fall


under this service.
BOUND SERVICES
• This type of android service allows the components of the application like activity to
bound themselves with it.

• Bound services perform their task as long as any application component is bound
to it.

• More than one component is allowed to bind themselves with a service at a time.

• In order to bind an application component with a service bindService() method is used.


THE LIFE CYCLE OF ANDROID SERVICES
• In android, services have 2 possible paths to complete its life cycle namely Started and Bounded.

• 1. Started Service (Unbounded Service):


• A service will initiate when an application component calls the
startService() method. Once initiated, the service can run continuously in
the background even if the component is destroyed which was responsible
for the start of the service. Two option are available to stop the execution of
service

• By calling stopService() method,


• The service can stop itself by using stopSelf() method.
THE LIFE CYCLE OF ANDROID
SERVICES
• 2. Bounded Service
• It can be treated as a server in a client-server interface. Android application components
can send requests to the service and can fetch results.
• A service is termed as bounded when an application component binds itself with a
service by calling bindService() method. To stop the execution of this service, all the
components must unbind themselves from the service by using unbindService() method.
• If a component starts the service by calling startService() (which results in a call to
onStartCommand()), the service continues to run until it stops itself with stopSelf() or
another component stops it by calling stopService().

• If a component calls bindService() to create the service and onStartCommand() is not


called, the service runs only as long as the component is bound to it. After the service is
unbound from all of its clients, the system destroys it.
THE LIFE CYCLE OF ANDROID SERVICES

• The Android system stops a service only when memory is low and it must recover
system resources for the activity that has user focus.
• If the service is bound to an activity that has user focus, it's less likely to be killed;
if the service is declared to run in the foreground, it's rarely killed.
• If the service is started and is long-running, the system lowers its position in the
list of background tasks over time, and the service becomes highly susceptible to
killing—if a service is started, one must design it to gracefully handle restarts by the
system.
• If the system kills a service, it restarts it as soon as resources become available, but
this also depends on the value that you return from onStartCommand().
The service lifecycle. The diagram on the left
shows the lifecycle when the service is created
with startService() and the diagram on the right
shows the lifecycle when the service is created
with bindService().
FUNDAMENTALS OF ANDROID
SERVICES
• A user-defined service can be created through a normal class which is extending the
class Service.

• Further, to carry out the operations of service on applications, there are certain
callback methods which are needed to be overridden.
SERVICES
Methods Description

The Android service calls this method when a component(eg: activity) requests
onStartCommand() to start a service using startService(). Once the service is started, it can be stopped
explicitly using stopService() or stopSelf() methods.

This method is mandatory to implement in android service and is


invoked whenever an application component calls the bindService() method in
onBind() order to bind itself with a service. User-interface is also provided to
communicate with the service effectively by returning an IBinder object. If the
binding of service is not required then the method must return null.
SERVICES
The Android system invokes this method when all the clients get disconnected from a particular service
onUnbind()
interface.

Once all clients are disconnected from the particular interface of service and there is a need to connect
onRebind()
the service with new clients, the system calls this method.

Whenever a service is created either using onStartCommand() or onBind(), the android system calls this
onCreate()
method. This method is necessary to perform a one-time-set-up.

When a service is no longer in use, the system invokes this method just before the service destroys as a
onDestroy() final clean up call. Services must implement this method in order to clean up resources like registered
listeners, threads, receivers, etc.
EXAMPLE OF ANDROID SERVICES
• Playing music in the background is a very common example of services in android.
• From the time when a user starts the service, music play continuously in the
background even if the user switches to another application.
• The user has to stop the service explicitly in order to pause the music.
• Below is the complete step-by-step implementation of this android service using a
few callback methods.
STEP 1: CREATE A NEW PROJECT

• Click on File, then New => New Project.


• Choose Empty Views Activity
• Select language as Java/Kotlin
• Select the minimum SDK as per your need.
STEP 2: MODIFY STRINGS.XML
FILE

• All the strings which are used in the activity are listed in this file.
<resources>
<string name="app_name">Services_In_Android</string>
<string name="heading">Services In Android</string>
<string name="startButtonText">Start the Service</string>
<string name="stopButtonText">Stop the Service</string>
</resources>
STEP 3: WORKING WITH THE ACTIVITY_MAIN.XML FILE

Open the activity_main.xml file and add 2


Buttons in it which will start and stop the
service.
STEP 4: CREATING THE CUSTOM SERVICE CLASS
// creating a media player which @Override
A custom service class will be created // will play the audio of Default // execution of the service will
in the same directory where the // ringtone in android device // stop on calling this method
MainActivity class resides and this class player = public void onDestroy() {
will extend the Service class.
MediaPlayer.create( this, super.onDestroy();
The callback methods are used toSettings.System.DEFAULT_RINGTONE_U
initiate and destroy the services. To playRI );
// stopping the process
music, the MediaPlayer object is used. // providing the boolean
player.stop();
// value as true to play
public class NewService extends Service { }
// the audio on loop
// declaring object of MediaPlayer @Nullable
player.setLooping( true );
private MediaPlayer player; @Override
// starting the process
@Override public IBinder onBind(Intent in
player.start();
// execution of service will start return null;
// returns the status
// on calling this method }
// of the program
public int onStartCommand(Intent intent, }
return START_STICKY;
int flags, int startId) {
STEP 5: WORKING WITH THE MAINACTIVITY
FILE
Now, the button objects will be declared and the process // buttons to make them respond
to be performed on clicking these buttons will be defined. // correctly according to the process
public class MainActivity extends AppCompatActivity implements start.setOnClickListener( this );
View.OnClickListener {
stop.setOnClickListener( this );
// declaring objects of Button class
}
private Button start, stop;
public void onClick(View view) {
@Override
// process to be performed // if start button is clicked
protected void onCreate(Bundle savedInstanceState) {
if(view == start){
super.onCreate( savedInstanceState );
// starting the service
setContentView( R.layout.activity_main );
startService(new Intent( this, NewService.class ) );
// assigning ID of startButton
}
// to the object start
// process to be performed // if stop button is clicked
start = (Button) findViewById( R.id.startButton );
else if (view == stop){
// assigning ID of stopButton
// stopping the service
// to the object stop
stopService(new Intent( this, NewService.class ) );
stop = (Button) findViewById( R.id.stopButton );
} }}
// declaring listeners for the
STEP 6: MODIFY THE ANDROIDMANIFEST.XML
FILE
To implement the services successfully on any android:theme="@style/AppTheme">
android device, it is necessary to mention the <activity android:name=".MainActivity">
created service in the AndroidManifest.xml file. It <intent-filter>
is not possible for a service to perform its task if it
<action
is not mentioned in this file. The service name is android:name="android.intent.action.MAIN" />
mentioned inside the application tag.
<category
<?xml version="1.0" encoding="utf-8"?> android:name="android.intent.category.LAUNCHER" />
<manifest </intent-filter>
xmlns:android="http://schemas.android.com/apk/res/androi
d" </activity>
package="com.example.services_in_android"> <meta-data
<application android:name="preloaded_fonts"
android:allowBackup="true" android:resource="@array/preloaded_fonts" />
<!-- Mention the service name here -->
android:icon="@mipmap/ic_launcher"
<service android:name=".NewService"/>
android:label="@string/app_name"
</application>
android:roundIcon="@mipmap/ic_launcher_round“
</manifest>

You might also like