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
4. Services Service - LifeCycle
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. 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