SlideShare a Scribd company logo
Services
Services
A service is a component of an application without a GUI that
performs long running operations in the background. Its life cycle
is independent from that of Activity for which a Service survives
the closure of all the Activity of the application.
All other components can connect to a service and interact.
There are 2 types of Service based on its lifecycle:
● Started: when a component invokes startService() the service
is initialized and runs in the background indefinitely even if the
component that started it is destroyed
● Bound: when a component invokes bindService() the Service
is attached to that component. More components can be
attached to the Service, and when all the components
attached are destroyed the Service is destroyed.
Service
Services
This separation is not clear because a component may engage to
an existing Started Service and this can survive over the
destruction of the component the Service is bound to.
A service by default runs on the same process and then on the
same Main Thread of Activity, so in otrder to avoid UI blocks, long
running operations should be executed in a Background Thread.
Pattern: use a Service only if you need to perform any operations
not related to user interaction. For user operations use simple
AsyncTask and Background Thread.
Es. To handle an MP3 player within the application is not
necessary to instantiate a service, unless this has to survive
beyond the closing of the Activity.
Service
Services
Service - LifeCycle
Services
● onStartCommand(): invoked when another component invokes
StartService(). The instance of the service is unique, so each
new call to StartService () does not create a new instance of
the Service, but is rerun the onStartCommand(). It is not
necessary to override it if you want to create a Bound Service.
● onBind(): abstract method that must return a IBinder to
retrieve the instance of the Service. If you do not want to
create a BoundService this method must return null.
● onCreate(): first creation callback method.
● onDestroy(): last lifecycle method used to free resources.
Service – LifeCycle Callbacks
Services
Like all main components the service must be declared in the
Manifest file.
<manifest>
<application>
<service android:name=".ExampleService" />
</application>
</manifest>
A Service may contain an IntentFilter to be started with an implicit
Intent, but this is not recommended because it may be initiated by
other applications unknowingly.
Pattern: if you enter an IntentFilter in the declaration of the
Service for creating implicit Intent through, add the attribute:
android:exported="false"
Manifest declaration
Services
A StartedService starts with the call to StartService (). To close a
StartedService call StopService() from the outside or
Service.stopSelf () internally when the operation is finished.
There are 2classes to create a Started Service:
● Service: it is the class that all the Services extend. You need
to create a WorkerThread because all the service is performed
in the Main Thread and this could block the GUI of any Activity
in the foreground on the same process. It can handle multiple
simultaneous requests.
● IntentService: specialization of Service that handles each
request in a WorkerThread. It is the best choice to handle
requests in series.
Started Service
Services
public class ExampleService extends Service{
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
Started Service - Service
Services
The Service.onStartCommand() method must return an integer
value. This tells the system how the Service will be managed and
destroyed.
● START_NOT_STICKY: Service is not rebuilt unless there are
pending Intent-to-manage.
● START_STICKY: Service is always recreated by switching to
Service.onStartCommand() as a parameter to a null Intent.
● START_REDELIVER_INTENT: Service is always recreated by
switching to Service.onStartCommand() the last Intent
received.
Started Service - Service
Services
An IntentService does the following:
● It creates a WorkerThread to perform all tasks in series
● It creates a queue of Intent to pass the implementation of the
IntentService.onHandleIntent() method
● It destroys itself when the queue is empty
● It provides an implementation of Service.onBind() that returns
null by default
● It provides a default implementation of
Service.onStartCommand() to manage the queue of requests
that then have to be sent to IntentService.onHandleIntent()
Started Service - IntentService
Services
public class ExampleService extends IntentService {
public ExampleService() {
super("ExampleService");
}
@Override
protected void onHandleIntent(Intent intent) {
}
}
Started Service - IntentService
Services
To communicate outside the feed, or manage the operations to
another component running in the same process you can create a
Bound Service.
A Bound Service is the server part of a client-server interface.
Communications between components of different processes
(and different applications) are possible using the interprocess
communications (IPC) through a special language called Android
Interface Definition Language (AIDL).
Bound Service
Services
To attach a Service the Service.onBind() method must return a
IBinder that provides the communications interface between the
Service and the other component.
There are 3 ways to bind the service:
● Binder: used in the case where the service is private to the
application and is executed on the same process.
● Messenger: used in the case of communication between
different processes. In this case a Handler manages the
Message be sent to the Service
● AIDL: used in a multiprocess environment and/or multi-
application. AIDL decomposes objects into primitive types so
that the system can send them in different processes. To use it
you need to create a file .aidl which is defined in the interface.
Bound Service
Services
● Create an instance of the Binder in the Service
● Return this instance in the Service.onBind() method
● Retrieve the Service in the client-side using the callback
ServiceConnection.onServiceConnected().
public class BoundService extends Service {
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
BoundService getService() {
return BoundService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
Bound Service - Binder
Services
public class BindingActivity extends Activity {
BoundService mService;
boolean mBound = false;
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, BoundService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
if (mBound)
unbindService(mConnection);
}
public void onButtonClick(View v) {
if (mBound)
mService.doSomething();
}
Bound Service - Binder
Services
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder
service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
}
Bound Service - Binder
Services
Bound Service - LifeCycle

More Related Content

PDF
Creating Android Services with Delphi and RAD Studio 10 Seattle
Jim McKeeth
 
PDF
MuleSoft Surat Live Demonstration Virtual Meetup#3 - Building JWT OAuth 2.0 C...
Jitendra Bafna
 
PDF
Introduction to React Native & Rendering Charts / Graphs
Rahat Khanna a.k.a mAppMechanic
 
PDF
MuleSoft Surat Live Demonstration Virtual Meetup#2 - Customer Hosted Mule Run...
Jitendra Bafna
 
PPTX
SignalR. Code, not toothpaste - TechDays Belgium 2012
Maarten Balliauw
 
PPTX
SignalR with asp.net
Martin Bodocky
 
PDF
Meetup dpjs react_api
Seydou N Ba
 
PDF
MuleSoft Surat Virtual Meetup#15 - Caching Scope, Caching Strategy and Jenkin...
Jitendra Bafna
 
Creating Android Services with Delphi and RAD Studio 10 Seattle
Jim McKeeth
 
MuleSoft Surat Live Demonstration Virtual Meetup#3 - Building JWT OAuth 2.0 C...
Jitendra Bafna
 
Introduction to React Native & Rendering Charts / Graphs
Rahat Khanna a.k.a mAppMechanic
 
MuleSoft Surat Live Demonstration Virtual Meetup#2 - Customer Hosted Mule Run...
Jitendra Bafna
 
SignalR. Code, not toothpaste - TechDays Belgium 2012
Maarten Balliauw
 
SignalR with asp.net
Martin Bodocky
 
Meetup dpjs react_api
Seydou N Ba
 
MuleSoft Surat Virtual Meetup#15 - Caching Scope, Caching Strategy and Jenkin...
Jitendra Bafna
 

What's hot (20)

PPTX
MuleSoft Surat Virtual Meetup#9 - RAML Reusability and Simplified
Jitendra Bafna
 
PDF
[React-Native Tutorial 10] Camera Roll / Gallery / Camera / Native Modules by...
Kobkrit Viriyayudhakorn
 
PDF
React Context API
NodeXperts
 
PPTX
Laravel Events And Queue
Vivek S
 
PPTX
Real time web with SignalR
Alessandro Melchiori
 
PDF
React custom renderers
Giovanni Jiayi Hu
 
PPTX
Making share point rock with angular and react
Joseph Jorden
 
PDF
MuleSoft Surat Virtual Meetup#21 - MuleSoft API and RAML Design Best Practice...
Jitendra Bafna
 
PDF
React Native - Getting Started
Tracy Lee
 
PDF
MuleSoft Surat Live Demonstration Virtual Meetup#5 - Salesforce Composite Con...
Jitendra Bafna
 
PPTX
Angular 4 - quick view
Michael Haberman
 
PDF
Domains in apikit
fedefortin
 
PPTX
Building Realtime Web Applications With ASP.NET SignalR
Shravan Kumar Kasagoni
 
PPTX
03 spring cloud eureka service discovery
Janani Velmurugan
 
PDF
MuleSoft Surat Virtual Meetup#6 - MuleSoft Project Template Using Maven Arche...
Jitendra Bafna
 
PPTX
Introduction to SignalR
Adam Mokan
 
PPTX
MuleSoft Kochi Meetup #5– Handling Mule Exceptions
sumitahuja94
 
PPTX
SignalR for ASP.NET Developers
Shivanand Arur
 
PPTX
Building Real Time Web Applications with SignalR (NoVA Code Camp 2015)
Kevin Griffin
 
PDF
MuleSoft Surat Live Demonstration Virtual Meetup#4 - Automate Anypoint VPC, V...
Jitendra Bafna
 
MuleSoft Surat Virtual Meetup#9 - RAML Reusability and Simplified
Jitendra Bafna
 
[React-Native Tutorial 10] Camera Roll / Gallery / Camera / Native Modules by...
Kobkrit Viriyayudhakorn
 
React Context API
NodeXperts
 
Laravel Events And Queue
Vivek S
 
Real time web with SignalR
Alessandro Melchiori
 
React custom renderers
Giovanni Jiayi Hu
 
Making share point rock with angular and react
Joseph Jorden
 
MuleSoft Surat Virtual Meetup#21 - MuleSoft API and RAML Design Best Practice...
Jitendra Bafna
 
React Native - Getting Started
Tracy Lee
 
MuleSoft Surat Live Demonstration Virtual Meetup#5 - Salesforce Composite Con...
Jitendra Bafna
 
Angular 4 - quick view
Michael Haberman
 
Domains in apikit
fedefortin
 
Building Realtime Web Applications With ASP.NET SignalR
Shravan Kumar Kasagoni
 
03 spring cloud eureka service discovery
Janani Velmurugan
 
MuleSoft Surat Virtual Meetup#6 - MuleSoft Project Template Using Maven Arche...
Jitendra Bafna
 
Introduction to SignalR
Adam Mokan
 
MuleSoft Kochi Meetup #5– Handling Mule Exceptions
sumitahuja94
 
SignalR for ASP.NET Developers
Shivanand Arur
 
Building Real Time Web Applications with SignalR (NoVA Code Camp 2015)
Kevin Griffin
 
MuleSoft Surat Live Demonstration Virtual Meetup#4 - Automate Anypoint VPC, V...
Jitendra Bafna
 
Ad

Similar to Android App Development - 08 Services (20)

PPTX
Android service, aidl - day 1
Utkarsh Mankad
 
PDF
Android service
Krazy Koder
 
PPTX
9 services
Ajayvorar
 
PPTX
Services I.pptx
RiziX3
 
PPTX
Android Training (Services)
Khaled Anaqwa
 
PDF
Embedded Android : System Development - Part IV (Android System Services)
Emertxe Information Technologies Pvt Ltd
 
PDF
Android service
DENNIS JUNG
 
PPTX
Android Service
Charile Tsai
 
PDF
INTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLE
Kalpana Mohan
 
PDF
Android Service Intro
Jintin Lin
 
PPTX
Android intents, notification and broadcast recievers
Utkarsh Mankad
 
PDF
Serviceについて
Yasutaka Kawamoto
 
PPTX
Inter Process Communication (IPC) in Android
Malwinder Singh
 
PDF
Android101
David Marques
 
PPTX
Day 15: Working in Background
Ahsanul Karim
 
PPTX
Project a day 3 services
Goran Djonovic
 
PPTX
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
34ShreyaChauhan
 
PDF
04 programmation mobile - android - (db, receivers, services...)
TECOS
 
PPTX
Android Services
Ahsanul Karim
 
PPTX
Binder: Android IPC
Shaul Rosenzwieg
 
Android service, aidl - day 1
Utkarsh Mankad
 
Android service
Krazy Koder
 
9 services
Ajayvorar
 
Services I.pptx
RiziX3
 
Android Training (Services)
Khaled Anaqwa
 
Embedded Android : System Development - Part IV (Android System Services)
Emertxe Information Technologies Pvt Ltd
 
Android service
DENNIS JUNG
 
Android Service
Charile Tsai
 
INTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLE
Kalpana Mohan
 
Android Service Intro
Jintin Lin
 
Android intents, notification and broadcast recievers
Utkarsh Mankad
 
Serviceについて
Yasutaka Kawamoto
 
Inter Process Communication (IPC) in Android
Malwinder Singh
 
Android101
David Marques
 
Day 15: Working in Background
Ahsanul Karim
 
Project a day 3 services
Goran Djonovic
 
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
34ShreyaChauhan
 
04 programmation mobile - android - (db, receivers, services...)
TECOS
 
Android Services
Ahsanul Karim
 
Binder: Android IPC
Shaul Rosenzwieg
 
Ad

More from Diego Grancini (13)

ODP
Android App Development - 14 location, media and notifications
Diego Grancini
 
ODP
Android App Development - 13 Broadcast receivers and app widgets
Diego Grancini
 
ODP
Android App Development - 12 animations
Diego Grancini
 
ODP
Android App Development - 11 Lists, grids, adapters, dialogs and toasts
Diego Grancini
 
ODP
Android App Development - 10 Content providers
Diego Grancini
 
ODP
Android App Development - 09 Storage
Diego Grancini
 
ODP
Android App Development - 07 Threading
Diego Grancini
 
ODP
Android App Development - 06 Fragments
Diego Grancini
 
ODP
Android App Development - 05 Action bar
Diego Grancini
 
ODP
Android App Development - 04 Views and layouts
Diego Grancini
 
ODP
Android App Development - 03 Resources
Diego Grancini
 
ODP
Android App Development - 02 Activity and intent
Diego Grancini
 
ODP
Android App Development - 01 Introduction
Diego Grancini
 
Android App Development - 14 location, media and notifications
Diego Grancini
 
Android App Development - 13 Broadcast receivers and app widgets
Diego Grancini
 
Android App Development - 12 animations
Diego Grancini
 
Android App Development - 11 Lists, grids, adapters, dialogs and toasts
Diego Grancini
 
Android App Development - 10 Content providers
Diego Grancini
 
Android App Development - 09 Storage
Diego Grancini
 
Android App Development - 07 Threading
Diego Grancini
 
Android App Development - 06 Fragments
Diego Grancini
 
Android App Development - 05 Action bar
Diego Grancini
 
Android App Development - 04 Views and layouts
Diego Grancini
 
Android App Development - 03 Resources
Diego Grancini
 
Android App Development - 02 Activity and intent
Diego Grancini
 
Android App Development - 01 Introduction
Diego Grancini
 

Android App Development - 08 Services

  • 2. Services A service is a component of an application without a GUI that performs long running operations in the background. Its life cycle is independent from that of Activity for which a Service survives the closure of all the Activity of the application. All other components can connect to a service and interact. There are 2 types of Service based on its lifecycle: ● Started: when a component invokes startService() the service is initialized and runs in the background indefinitely even if the component that started it is destroyed ● Bound: when a component invokes bindService() the Service is attached to that component. More components can be attached to the Service, and when all the components attached are destroyed the Service is destroyed. Service
  • 3. Services This separation is not clear because a component may engage to an existing Started Service and this can survive over the destruction of the component the Service is bound to. A service by default runs on the same process and then on the same Main Thread of Activity, so in otrder to avoid UI blocks, long running operations should be executed in a Background Thread. Pattern: use a Service only if you need to perform any operations not related to user interaction. For user operations use simple AsyncTask and Background Thread. Es. To handle an MP3 player within the application is not necessary to instantiate a service, unless this has to survive beyond the closing of the Activity. Service
  • 5. Services ● onStartCommand(): invoked when another component invokes StartService(). The instance of the service is unique, so each new call to StartService () does not create a new instance of the Service, but is rerun the onStartCommand(). It is not necessary to override it if you want to create a Bound Service. ● onBind(): abstract method that must return a IBinder to retrieve the instance of the Service. If you do not want to create a BoundService this method must return null. ● onCreate(): first creation callback method. ● onDestroy(): last lifecycle method used to free resources. Service – LifeCycle Callbacks
  • 6. Services Like all main components the service must be declared in the Manifest file. <manifest> <application> <service android:name=".ExampleService" /> </application> </manifest> A Service may contain an IntentFilter to be started with an implicit Intent, but this is not recommended because it may be initiated by other applications unknowingly. Pattern: if you enter an IntentFilter in the declaration of the Service for creating implicit Intent through, add the attribute: android:exported="false" Manifest declaration
  • 7. Services A StartedService starts with the call to StartService (). To close a StartedService call StopService() from the outside or Service.stopSelf () internally when the operation is finished. There are 2classes to create a Started Service: ● Service: it is the class that all the Services extend. You need to create a WorkerThread because all the service is performed in the Main Thread and this could block the GUI of any Activity in the foreground on the same process. It can handle multiple simultaneous requests. ● IntentService: specialization of Service that handles each request in a WorkerThread. It is the best choice to handle requests in series. Started Service
  • 8. Services public class ExampleService extends Service{ @Override public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onDestroy() { super.onDestroy(); } } Started Service - Service
  • 9. Services The Service.onStartCommand() method must return an integer value. This tells the system how the Service will be managed and destroyed. ● START_NOT_STICKY: Service is not rebuilt unless there are pending Intent-to-manage. ● START_STICKY: Service is always recreated by switching to Service.onStartCommand() as a parameter to a null Intent. ● START_REDELIVER_INTENT: Service is always recreated by switching to Service.onStartCommand() the last Intent received. Started Service - Service
  • 10. Services An IntentService does the following: ● It creates a WorkerThread to perform all tasks in series ● It creates a queue of Intent to pass the implementation of the IntentService.onHandleIntent() method ● It destroys itself when the queue is empty ● It provides an implementation of Service.onBind() that returns null by default ● It provides a default implementation of Service.onStartCommand() to manage the queue of requests that then have to be sent to IntentService.onHandleIntent() Started Service - IntentService
  • 11. Services public class ExampleService extends IntentService { public ExampleService() { super("ExampleService"); } @Override protected void onHandleIntent(Intent intent) { } } Started Service - IntentService
  • 12. Services To communicate outside the feed, or manage the operations to another component running in the same process you can create a Bound Service. A Bound Service is the server part of a client-server interface. Communications between components of different processes (and different applications) are possible using the interprocess communications (IPC) through a special language called Android Interface Definition Language (AIDL). Bound Service
  • 13. Services To attach a Service the Service.onBind() method must return a IBinder that provides the communications interface between the Service and the other component. There are 3 ways to bind the service: ● Binder: used in the case where the service is private to the application and is executed on the same process. ● Messenger: used in the case of communication between different processes. In this case a Handler manages the Message be sent to the Service ● AIDL: used in a multiprocess environment and/or multi- application. AIDL decomposes objects into primitive types so that the system can send them in different processes. To use it you need to create a file .aidl which is defined in the interface. Bound Service
  • 14. Services ● Create an instance of the Binder in the Service ● Return this instance in the Service.onBind() method ● Retrieve the Service in the client-side using the callback ServiceConnection.onServiceConnected(). public class BoundService extends Service { private final IBinder mBinder = new LocalBinder(); public class LocalBinder extends Binder { BoundService getService() { return BoundService.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } } Bound Service - Binder
  • 15. Services public class BindingActivity extends Activity { BoundService mService; boolean mBound = false; @Override protected void onStart() { super.onStart(); Intent intent = new Intent(this, BoundService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); if (mBound) unbindService(mConnection); } public void onButtonClick(View v) { if (mBound) mService.doSomething(); } Bound Service - Binder
  • 16. Services private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; } @Override public void onServiceDisconnected(ComponentName arg0) { mBound = false; } }; } Bound Service - Binder