SlideShare a Scribd company logo
1 of 17
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

What's hot

MuleSoft Surat Virtual Meetup#9 - RAML Reusability and Simplified
MuleSoft Surat Virtual Meetup#9 - RAML Reusability and SimplifiedMuleSoft Surat Virtual Meetup#9 - RAML Reusability and Simplified
MuleSoft Surat Virtual Meetup#9 - RAML Reusability and SimplifiedJitendra Bafna
 
[React-Native Tutorial 10] Camera Roll / Gallery / Camera / Native Modules by...
[React-Native Tutorial 10] Camera Roll / Gallery / Camera / Native Modules by...[React-Native Tutorial 10] Camera Roll / Gallery / Camera / Native Modules by...
[React-Native Tutorial 10] Camera Roll / Gallery / Camera / Native Modules by...Kobkrit Viriyayudhakorn
 
React Context API
React Context APIReact Context API
React Context APINodeXperts
 
Laravel Events And Queue
Laravel Events And QueueLaravel Events And Queue
Laravel Events And QueueVivek S
 
Making share point rock with angular and react
Making share point rock with angular and reactMaking share point rock with angular and react
Making share point rock with angular and reactJoseph Jorden
 
MuleSoft Surat Virtual Meetup#21 - MuleSoft API and RAML Design Best Practice...
MuleSoft Surat Virtual Meetup#21 - MuleSoft API and RAML Design Best Practice...MuleSoft Surat Virtual Meetup#21 - MuleSoft API and RAML Design Best Practice...
MuleSoft Surat Virtual Meetup#21 - MuleSoft API and RAML Design Best Practice...Jitendra Bafna
 
React Native - Getting Started
React Native - Getting StartedReact Native - Getting Started
React Native - Getting StartedTracy Lee
 
MuleSoft Surat Live Demonstration Virtual Meetup#5 - Salesforce Composite Con...
MuleSoft Surat Live Demonstration Virtual Meetup#5 - Salesforce Composite Con...MuleSoft Surat Live Demonstration Virtual Meetup#5 - Salesforce Composite Con...
MuleSoft Surat Live Demonstration Virtual Meetup#5 - Salesforce Composite Con...Jitendra Bafna
 
Domains in apikit
Domains in apikitDomains in apikit
Domains in apikitfedefortin
 
Building Realtime Web Applications With ASP.NET SignalR
Building Realtime Web Applications With ASP.NET SignalRBuilding Realtime Web Applications With ASP.NET SignalR
Building Realtime Web Applications With ASP.NET SignalRShravan Kumar Kasagoni
 
03 spring cloud eureka service discovery
03 spring cloud eureka   service discovery03 spring cloud eureka   service discovery
03 spring cloud eureka service discoveryJanani Velmurugan
 
MuleSoft Surat Virtual Meetup#6 - MuleSoft Project Template Using Maven Arche...
MuleSoft Surat Virtual Meetup#6 - MuleSoft Project Template Using Maven Arche...MuleSoft Surat Virtual Meetup#6 - MuleSoft Project Template Using Maven Arche...
MuleSoft Surat Virtual Meetup#6 - MuleSoft Project Template Using Maven Arche...Jitendra Bafna
 
Introduction to SignalR
Introduction to SignalRIntroduction to SignalR
Introduction to SignalRAdam Mokan
 
MuleSoft Kochi Meetup #5– Handling Mule Exceptions
MuleSoft Kochi Meetup #5– Handling Mule ExceptionsMuleSoft Kochi Meetup #5– Handling Mule Exceptions
MuleSoft Kochi Meetup #5– Handling Mule Exceptionssumitahuja94
 
SignalR for ASP.NET Developers
SignalR for ASP.NET DevelopersSignalR for ASP.NET Developers
SignalR for ASP.NET DevelopersShivanand Arur
 
Building Real Time Web Applications with SignalR (NoVA Code Camp 2015)
Building Real Time Web Applications with SignalR (NoVA Code Camp 2015)Building Real Time Web Applications with SignalR (NoVA Code Camp 2015)
Building Real Time Web Applications with SignalR (NoVA Code Camp 2015)Kevin Griffin
 
MuleSoft Surat Live Demonstration Virtual Meetup#4 - Automate Anypoint VPC, V...
MuleSoft Surat Live Demonstration Virtual Meetup#4 - Automate Anypoint VPC, V...MuleSoft Surat Live Demonstration Virtual Meetup#4 - Automate Anypoint VPC, V...
MuleSoft Surat Live Demonstration Virtual Meetup#4 - Automate Anypoint VPC, V...Jitendra Bafna
 

What's hot (20)

MuleSoft Surat Virtual Meetup#9 - RAML Reusability and Simplified
MuleSoft Surat Virtual Meetup#9 - RAML Reusability and SimplifiedMuleSoft Surat Virtual Meetup#9 - RAML Reusability and Simplified
MuleSoft Surat Virtual Meetup#9 - RAML Reusability and Simplified
 
[React-Native Tutorial 10] Camera Roll / Gallery / Camera / Native Modules by...
[React-Native Tutorial 10] Camera Roll / Gallery / Camera / Native Modules by...[React-Native Tutorial 10] Camera Roll / Gallery / Camera / Native Modules by...
[React-Native Tutorial 10] Camera Roll / Gallery / Camera / Native Modules by...
 
React Context API
React Context APIReact Context API
React Context API
 
Laravel Events And Queue
Laravel Events And QueueLaravel Events And Queue
Laravel Events And Queue
 
Real time web with SignalR
Real time web with SignalRReal time web with SignalR
Real time web with SignalR
 
React custom renderers
React custom renderersReact custom renderers
React custom renderers
 
Making share point rock with angular and react
Making share point rock with angular and reactMaking share point rock with angular and react
Making share point rock with angular and react
 
MuleSoft Surat Virtual Meetup#21 - MuleSoft API and RAML Design Best Practice...
MuleSoft Surat Virtual Meetup#21 - MuleSoft API and RAML Design Best Practice...MuleSoft Surat Virtual Meetup#21 - MuleSoft API and RAML Design Best Practice...
MuleSoft Surat Virtual Meetup#21 - MuleSoft API and RAML Design Best Practice...
 
React Native - Getting Started
React Native - Getting StartedReact Native - Getting Started
React Native - Getting Started
 
MuleSoft Surat Live Demonstration Virtual Meetup#5 - Salesforce Composite Con...
MuleSoft Surat Live Demonstration Virtual Meetup#5 - Salesforce Composite Con...MuleSoft Surat Live Demonstration Virtual Meetup#5 - Salesforce Composite Con...
MuleSoft Surat Live Demonstration Virtual Meetup#5 - Salesforce Composite Con...
 
Angular 4 - quick view
Angular 4 - quick viewAngular 4 - quick view
Angular 4 - quick view
 
Domains in apikit
Domains in apikitDomains in apikit
Domains in apikit
 
Building Realtime Web Applications With ASP.NET SignalR
Building Realtime Web Applications With ASP.NET SignalRBuilding Realtime Web Applications With ASP.NET SignalR
Building Realtime Web Applications With ASP.NET SignalR
 
03 spring cloud eureka service discovery
03 spring cloud eureka   service discovery03 spring cloud eureka   service discovery
03 spring cloud eureka service discovery
 
MuleSoft Surat Virtual Meetup#6 - MuleSoft Project Template Using Maven Arche...
MuleSoft Surat Virtual Meetup#6 - MuleSoft Project Template Using Maven Arche...MuleSoft Surat Virtual Meetup#6 - MuleSoft Project Template Using Maven Arche...
MuleSoft Surat Virtual Meetup#6 - MuleSoft Project Template Using Maven Arche...
 
Introduction to SignalR
Introduction to SignalRIntroduction to SignalR
Introduction to SignalR
 
MuleSoft Kochi Meetup #5– Handling Mule Exceptions
MuleSoft Kochi Meetup #5– Handling Mule ExceptionsMuleSoft Kochi Meetup #5– Handling Mule Exceptions
MuleSoft Kochi Meetup #5– Handling Mule Exceptions
 
SignalR for ASP.NET Developers
SignalR for ASP.NET DevelopersSignalR for ASP.NET Developers
SignalR for ASP.NET Developers
 
Building Real Time Web Applications with SignalR (NoVA Code Camp 2015)
Building Real Time Web Applications with SignalR (NoVA Code Camp 2015)Building Real Time Web Applications with SignalR (NoVA Code Camp 2015)
Building Real Time Web Applications with SignalR (NoVA Code Camp 2015)
 
MuleSoft Surat Live Demonstration Virtual Meetup#4 - Automate Anypoint VPC, V...
MuleSoft Surat Live Demonstration Virtual Meetup#4 - Automate Anypoint VPC, V...MuleSoft Surat Live Demonstration Virtual Meetup#4 - Automate Anypoint VPC, V...
MuleSoft Surat Live Demonstration Virtual Meetup#4 - Automate Anypoint VPC, V...
 

Similar to Manage services in Android apps

Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1Utkarsh Mankad
 
Android Training (Services)
Android Training (Services)Android Training (Services)
Android Training (Services)Khaled Anaqwa
 
Services I.pptx
Services I.pptxServices I.pptx
Services I.pptxRiziX3
 
Android intents, notification and broadcast recievers
Android intents, notification and broadcast recieversAndroid intents, notification and broadcast recievers
Android intents, notification and broadcast recieversUtkarsh Mankad
 
Android service and gcm
Android service and gcmAndroid service and gcm
Android service and gcmRan Zeller
 
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxxMAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx34ShreyaChauhan
 
Inter Process Communication (IPC) in Android
Inter Process Communication (IPC) in AndroidInter Process Communication (IPC) in Android
Inter Process Communication (IPC) in AndroidMalwinder Singh
 
Day 15: Working in Background
Day 15: Working in BackgroundDay 15: Working in Background
Day 15: Working in BackgroundAhsanul Karim
 
Android Service Intro
Android Service IntroAndroid Service Intro
Android Service IntroJintin Lin
 
Android 8 behavior changes
Android 8 behavior changesAndroid 8 behavior changes
Android 8 behavior changesInnovationM
 

Similar to Manage services in Android apps (20)

Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1
 
Android Training (Services)
Android Training (Services)Android Training (Services)
Android Training (Services)
 
Services I.pptx
Services I.pptxServices I.pptx
Services I.pptx
 
Android intents, notification and broadcast recievers
Android intents, notification and broadcast recieversAndroid intents, notification and broadcast recievers
Android intents, notification and broadcast recievers
 
Android service
Android serviceAndroid service
Android service
 
Android service and gcm
Android service and gcmAndroid service and gcm
Android service and gcm
 
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxxMAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
 
Inter Process Communication (IPC) in Android
Inter Process Communication (IPC) in AndroidInter Process Communication (IPC) in Android
Inter Process Communication (IPC) in Android
 
Aidl service
Aidl serviceAidl service
Aidl service
 
Day 15: Working in Background
Day 15: Working in BackgroundDay 15: Working in Background
Day 15: Working in Background
 
Guice
GuiceGuice
Guice
 
Guice
GuiceGuice
Guice
 
Android Service Intro
Android Service IntroAndroid Service Intro
Android Service Intro
 
Guice
GuiceGuice
Guice
 
Guice
GuiceGuice
Guice
 
sfdsdfsdfsdf
sfdsdfsdfsdfsfdsdfsdfsdf
sfdsdfsdfsdf
 
Android 8 behavior changes
Android 8 behavior changesAndroid 8 behavior changes
Android 8 behavior changes
 
Grails services
Grails servicesGrails services
Grails services
 
Android Services
Android ServicesAndroid Services
Android Services
 
Grails services
Grails servicesGrails services
Grails services
 

More from Diego Grancini

Android App Development - 14 location, media and notifications
Android App Development - 14 location, media and notificationsAndroid App Development - 14 location, media and notifications
Android App Development - 14 location, media and notificationsDiego Grancini
 
Android App Development - 13 Broadcast receivers and app widgets
Android App Development - 13 Broadcast receivers and app widgetsAndroid App Development - 13 Broadcast receivers and app widgets
Android App Development - 13 Broadcast receivers and app widgetsDiego Grancini
 
Android App Development - 12 animations
Android App Development - 12 animationsAndroid App Development - 12 animations
Android App Development - 12 animationsDiego Grancini
 
Android App Development - 11 Lists, grids, adapters, dialogs and toasts
Android App Development - 11 Lists, grids, adapters, dialogs and toastsAndroid App Development - 11 Lists, grids, adapters, dialogs and toasts
Android App Development - 11 Lists, grids, adapters, dialogs and toastsDiego Grancini
 
Android App Development - 10 Content providers
Android App Development - 10 Content providersAndroid App Development - 10 Content providers
Android App Development - 10 Content providersDiego Grancini
 
Android App Development - 09 Storage
Android App Development - 09 StorageAndroid App Development - 09 Storage
Android App Development - 09 StorageDiego Grancini
 
Android App Development - 07 Threading
Android App Development - 07 ThreadingAndroid App Development - 07 Threading
Android App Development - 07 ThreadingDiego Grancini
 
Android App Development - 06 Fragments
Android App Development - 06 FragmentsAndroid App Development - 06 Fragments
Android App Development - 06 FragmentsDiego Grancini
 
Android App Development - 05 Action bar
Android App Development - 05 Action barAndroid App Development - 05 Action bar
Android App Development - 05 Action barDiego Grancini
 
Android App Development - 04 Views and layouts
Android App Development - 04 Views and layoutsAndroid App Development - 04 Views and layouts
Android App Development - 04 Views and layoutsDiego Grancini
 
Android App Development - 03 Resources
Android App Development - 03 ResourcesAndroid App Development - 03 Resources
Android App Development - 03 ResourcesDiego Grancini
 
Android App Development - 02 Activity and intent
Android App Development - 02 Activity and intentAndroid App Development - 02 Activity and intent
Android App Development - 02 Activity and intentDiego Grancini
 
Android App Development - 01 Introduction
Android App Development - 01 IntroductionAndroid App Development - 01 Introduction
Android App Development - 01 IntroductionDiego Grancini
 

More from Diego Grancini (13)

Android App Development - 14 location, media and notifications
Android App Development - 14 location, media and notificationsAndroid App Development - 14 location, media and notifications
Android App Development - 14 location, media and notifications
 
Android App Development - 13 Broadcast receivers and app widgets
Android App Development - 13 Broadcast receivers and app widgetsAndroid App Development - 13 Broadcast receivers and app widgets
Android App Development - 13 Broadcast receivers and app widgets
 
Android App Development - 12 animations
Android App Development - 12 animationsAndroid App Development - 12 animations
Android App Development - 12 animations
 
Android App Development - 11 Lists, grids, adapters, dialogs and toasts
Android App Development - 11 Lists, grids, adapters, dialogs and toastsAndroid App Development - 11 Lists, grids, adapters, dialogs and toasts
Android App Development - 11 Lists, grids, adapters, dialogs and toasts
 
Android App Development - 10 Content providers
Android App Development - 10 Content providersAndroid App Development - 10 Content providers
Android App Development - 10 Content providers
 
Android App Development - 09 Storage
Android App Development - 09 StorageAndroid App Development - 09 Storage
Android App Development - 09 Storage
 
Android App Development - 07 Threading
Android App Development - 07 ThreadingAndroid App Development - 07 Threading
Android App Development - 07 Threading
 
Android App Development - 06 Fragments
Android App Development - 06 FragmentsAndroid App Development - 06 Fragments
Android App Development - 06 Fragments
 
Android App Development - 05 Action bar
Android App Development - 05 Action barAndroid App Development - 05 Action bar
Android App Development - 05 Action bar
 
Android App Development - 04 Views and layouts
Android App Development - 04 Views and layoutsAndroid App Development - 04 Views and layouts
Android App Development - 04 Views and layouts
 
Android App Development - 03 Resources
Android App Development - 03 ResourcesAndroid App Development - 03 Resources
Android App Development - 03 Resources
 
Android App Development - 02 Activity and intent
Android App Development - 02 Activity and intentAndroid App Development - 02 Activity and intent
Android App Development - 02 Activity and intent
 
Android App Development - 01 Introduction
Android App Development - 01 IntroductionAndroid App Development - 01 Introduction
Android App Development - 01 Introduction
 

Recently uploaded

CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceanilsa9823
 
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRFULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRnishacall1
 
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceanilsa9823
 
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceDelhi Call girls
 
9892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x79892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x7Pooja Nehwal
 
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Pooja Nehwal
 
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPowerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPsychicRuben LoveSpells
 

Recently uploaded (7)

CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
 
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRFULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
 
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
 
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
 
9892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x79892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x7
 
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
 
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPowerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
 

Manage services in Android apps

  • 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