Android Services Lecture 4 Operating Systems Practical 26 October 2016 This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by/4.0/. OSP Android Services, Lecture 4 1/55
Overview Started Services Bound Services Messenger AIDL Foreground Services Bibliography OSP Android Services, Lecture 4 2/55
Outline Overview Started Services Bound Services Messenger AIDL Foreground Services Bibliography OSP Android Services, Lecture 4 3/55
Android Service Application component without a user interface Designed for long-running operations in the background Can run even if the user is not in the hosting application OSP Android Services, Lecture 4 4/55
Android Service Can be accessed by external applications directly If exported by the hosting application By default, runs in the main UI thread of the hosting application CPU intensive and blocking operations - create another thread A service can be configured to run in a separate process OSP Android Services, Lecture 4 5/55
Declaring a Service in Manifest <service> tag under the <application> tag android:name - The class implementing the service android:enabled - Set as true or false if the system can / cannot instantiate the service Default value is true OSP Android Services, Lecture 4 6/55
Declaring a Service in Manifest android:exported - Whether or not other applications can access the service Without intent filter - default is false With intent filter - default is true android:process - Create a new process to run the service E.g. android:process=":fgservice" android:permission - Permission that must be given to a component to access the service OSP Android Services, Lecture 4 7/55
Types of Services Started Service Performs a single operation Does not return the result to the caller directly Launched by an application component that calls Context.startService() Once started, it can run indefinitely, even if the caller has terminated Not killed when they finish their job OSP Android Services, Lecture 4 8/55
Types of Services Bound Service Can perform multiple operations Offers a client-server interface, allowing interactions with it (send requests, obtain results) Communication can be across processes (IPC) Launched by an application component that calls Context.bindService() Remains active as long as there is at least one component is still bound to it Killed when the last component calls Context.unbindService() OSP Android Services, Lecture 4 9/55
Service Life Cycle Source: http://developer.android.com OSP Android Services, Lecture 4 10/55
Outline Overview Started Services Bound Services Messenger AIDL Foreground Services Bibliography OSP Android Services, Lecture 4 11/55
Started Services Launched by calling Context.startService(Intent) Intent - specify the task given to the Service In extras or action Read information in onstartcommand() Not terminated after the task is completed Stopped in two ways: Another application component - Context.stopService(Intent) Stop itself - Service.stopSelf() OSP Android Services, Lecture 4 12/55
Implementing a Started Service Extending the base Service class Implement the onstartcommand(intent, flags, startid) method Separate thread for CPU intensive / blocking operations START STICKY - restart faster START NOT STICKY - killed faster onbind() is mandatory - return null OSP Android Services, Lecture 4 13/55
Service Example p u b l i c c l a s s H e l l o S e r v i c e extends S e r v i c e { @ O v e r r i d e p u b l i c i n t onstartcommand ( I n t e n t i n t e n t, i n t f l a g s, i n t s t a r t I d ) { Toast. maketext ( t h i s, s e r v i c e s t a r t i n g, Toast. LENGTH SHORT ). show ( ) ; r e t u r n START STICKY ; @ O v e r r i d e p u b l i c I B i n d e r onbind ( I n t e n t i n t e n t ) { r e t u r n n u l l ; @ O v e r r i d e p u b l i c v o i d ondestroy ( ) { Toast. maketext ( t h i s, s e r v i c e done, Toast. LENGTH SHORT ). show ( ) ; OSP Android Services, Lecture 4 14/55
Implementing a Started Service Extending the IntentService class Uses a worker thread to handle start requests, one at a time Multiple requests, not handled simultaneously Only onhandleintent(intent) is mandatory OSP Android Services, Lecture 4 15/55
IntentService Creates a worker thread that will treat all Intents received by onstartcommand() Creates a work queue that delivers one Intent at a time to onhandleintent() Stops service after handling all requests Includes onbind() that returns null Includes onstartcommand() that sends Intents to the work queue and then to onhandleintent() OSP Android Services, Lecture 4 16/55
IntentService Example p u b l i c c l a s s H e l l o I n t e n t S e r v i c e extends I n t e n t S e r v i c e { p u b l i c H e l l o I n t e n t S e r v i c e ( ) { s u p e r ( H e l l o I n t e n t S e r v i c e ) ; @ O v e r r i d e p r o t e c t e d v o i d o n H a n d l e I n t e n t ( I n t e n t i n t e n t ) { // Normally we would do some work here, l i k e download a f i l e. Constructor and implementation for onhandleintent() When overriding other callback methods - call super OSP Android Services, Lecture 4 17/55
Starting a Service Pass an Intent to startservice() The system calls the service s oncreate(), then onstartcommand() If the service is running, it calls only onstartcommand() I n t e n t i n t e n t = new I n t e n t ( t h i s, H e l l o S e r v i c e. c l a s s ) ; s t a r t S e r v i c e ( i n t e n t ) ; OSP Android Services, Lecture 4 18/55
Stopping a Started Service Manage its own lifecycle Destroyed by the system only in low memory situations Call stopself() from the service Call stopservice() from other component Should not kill the service while processing requests stopself() using startid OSP Android Services, Lecture 4 19/55
Outline Overview Started Services Bound Services Messenger AIDL Foreground Services Bibliography OSP Android Services, Lecture 4 20/55
Bound Services Launched by calling Context.bindService(Intent) If another component calls bindservice() after the service has been launched, the same service instance is given Client-server paradigm The server is the running service The client is the application component (e.g. the Activity) bound to the service The communication interface is specified by an IBinder Can receive requests from external processes / applications OSP Android Services, Lecture 4 21/55
Implementing a Bound Service Extend the Service class Implement the onbind() method onbind() returns an IBinder object Called only for the first component binding to the service Subsequent components that bind to the service will receive the same IBinder object OSP Android Services, Lecture 4 22/55
Communicating with a Bound Service If the client is running in the same process Extend the Binder class and return an instance For communicating with external processes you can: Use a Messenger (that serializes incoming requests) and call Messenger.getBinder() Use AIDL (especially when you need to handle multiple requests simultaneously) OSP Android Services, Lecture 4 23/55
Client Side - Connecting to a Bound Service Implement the ServiceConnection interface onserviceconnected() callback gives the IBinder used to call remote methods onservicedisconnected() callback gets called when the connection to the service has died OSP Android Services, Lecture 4 24/55
Client Side - Connecting to a Bound Service Call bindservice() and give it an instance of your ServiceConnection implementation bindservice() returns immediately The framework will call onserviceconnected() when connection to the service has been established OSP Android Services, Lecture 4 25/55
Client Side - Disconnecting from a Bound Service Call unbindservice() to end service connection If the current component unbinding is the only one who had been still bound, the service should be destroyed The service is kept alive only if it is also a Started Service (another component has called startservice() on it) OSP Android Services, Lecture 4 26/55
Extending the Binder class Client and service in the same process In the Service class, create a member variable of a class extending Binder From the Service s onbind() return the member variable OSP Android Services, Lecture 4 27/55
Extending the Binder class 3 options for exporting services: The Binder instance has public methods that can be called from the outside It can return a reference to the Service class, which itself has public methods It can return a reference to another class, hosted within the service, which has public methods OSP Android Services, Lecture 4 28/55
Using a reference to the Service p u b l i c c l a s s L o c a l S e r v i c e extends S e r v i c e { private f i n a l IBinder mbinder = new LocalBinder ( ) ; private f i n a l Random mgenerator = new Random ( ) ; public c l a s s L o c a l B i n d e r extends B i n d e r { L o c a l S e r v i c e g e t S e r v i c e ( ) { r e t u r n L o c a l S e r v i c e. t h i s ; @ O v e r r i d e p u b l i c I B i n d e r onbind ( I n t e n t i n t e n t ) { r e t u r n mbinder ; public i n t getrandomnumber ( ) { r e t u r n mgenerator. n e x t I n t ( 1 0 0 ) ; OSP Android Services, Lecture 4 29/55
Using a reference to the Service p u b l i c c l a s s B i n d i n g A c t i v i t y extends A c t i v i t y { L o c a l S e r v i c e m S e r v i c e ; boolean mbound = f a l s e ; @ O v e r r i d e p r o t e c t e d v o i d onstart ( ) { s u p e r. o n S t a r t ( ) ; I n t e n t i n t e n t = new I n t e n t ( t h i s, L o c a l S e r v i c e. c l a s s ) ; bindservice ( intent, mconnection, Context. BIND AUTO CREATE ) ; @ O v e r r i d e p r o t e c t e d v o i d onstop ( ) { s u p e r. onstop ( ) ; i f ( mbound ) { u n b i n d S e r v i c e ( mconnection ) ; mbound = f a l s e ; p r i v a t e S e r v i c e C o n n e c t i o n mconnection = new S e r v i c e C o n n e c t i o n ( ) { @ O v e r r i d e p u b l i c v o i d onserviceconnected ( ComponentName classname, IBinder s e r v i c e ) { L o c a l B i n d e r b i n d e r = ( L o c a l B i n d e r ) s e r v i c e ; m S e r v i c e = b i n d e r. g e t S e r v i c e ( ) ; mbound = true ; @ O v e r r i d e p u b l i c v o i d onservicedisconnected ( ComponentName arg0 ) { mbound = f a l s e ; ; OSP Android Services, Lecture 4 30/55
Outline Overview Started Services Bound Services Messenger AIDL Foreground Services Bibliography OSP Android Services, Lecture 4 31/55
Communicating through a Messenger Communication between bound service and external application Through a Messenger IPC Serialize multiple incoming connections OSP Android Services, Lecture 4 32/55
Communicating through a Messenger In the Service class, create a member variable of a class extending Handler Implement the handlemessage(message) method Communication with the service is done by how different Message types are handled Create a Messenger member variable passing to its constructor an instance of your Handler class In the onbind() method return Messenger.getBinder() OSP Android Services, Lecture 4 33/55
Messenger Example p u b l i c c l a s s M e s s e n g e r S e r v i c e extends S e r v i c e { s t a t i c f i n a l i n t MSG SAY HELLO = 1 ; c l a s s I n c o m i n g H a n d l e r extends H a n d l e r { @ O v e r r i d e p u b l i c v o i d handlemessage ( Message msg ) { s w i t c h ( msg. what ) { case MSG SAY HELLO : Toast. maketext ( g e t A p p l i c a t i o n C o n t e x t ( ), h e l l o!, Toast. LENGTH SHORT ). show ( ) ; break ; default : s u p e r. handlemessage ( msg ) ; f i n a l Messenger mmessenger = new Messenger (new IncomingHandler ( ) ) ; @ O v e r r i d e p u b l i c I B i n d e r onbind ( I n t e n t i n t e n t ) { r e t u r n mmessenger. g e t B i n d e r ( ) ; OSP Android Services, Lecture 4 34/55
Communicating through a Messenger Client side In onserviceconnected() receive IBinder object Create Messenger object based on IBinder object Create and send messages through the Messenger OSP Android Services, Lecture 4 35/55
Messenger Example p u b l i c c l a s s A c t i v i t y M e s s e n g e r extends A c t i v i t y { Messenger m S e r v i c e = n u l l ; boolean mbound ; p r i v a t e S e r v i c e C o n n e c t i o n mconnection = new S e r v i c e C o n n e c t i o n ( ) { p u b l i c v o i d onserviceconnected ( ComponentName classname, IBinder s e r v i c e ) { m S e r v i c e = new Messenger ( s e r v i c e ) ; mbound = true ; ; p u b l i c v o i d onservicedisconnected ( ComponentName classname ) { m S e r v i c e = n u l l ; mbound = f a l s e ; p u b l i c v o i d sayhello ( View v ) { i f (! mbound ) r e t u r n ; Message msg = Message. obtain ( null, MessengerService. MSG SAY HELLO, 0, 0 ) ; t r y { m S e r v i c e. send ( msg ) ; catch ( RemoteException e ) { e. p r i n t S t a c k T r a c e ( ) ; OSP Android Services, Lecture 4 36/55
Communicating through a Messenger The handlemessage() method returns void The service has no readily-available means to respond to the client To have two-way communication you need to implement a similar Messenger mechanism in the client Set the client s Messenger as the replyto parameter of the Message The service receives a reference to the client s Messenger that can be used to send it s responses OSP Android Services, Lecture 4 37/55
Outline Overview Started Services Bound Services Messenger AIDL Foreground Services Bibliography OSP Android Services, Lecture 4 38/55
Interface Definition Languages Communication between components written in different languages Specification language Describe a software component s interface Remote Procedure Calls (RPC) OSP Android Services, Lecture 4 39/55
Interface Definition Languages Examples of IDLs include: AIDL - Android IDL OMG IDL (Object Management Group IDL) - implemented in CORBA for RPC services Protocol Buffers - Google s method of serializing structured data WSDL - Web Services Description Language OSP Android Services, Lecture 4 40/55
The Need for AIDL Android provides security through sandboxing An app s process cannot normally access the memory of another app s process Communication between two processes Send messages, perform RPC Decompose objects into primitives that can be marshalled across the system The Binder system handles these operations Expose Binder functionality to applications Using AIDL System marshalls / unmarshalls objects and calls the Binder services OSP Android Services, Lecture 4 41/55
Creating an AIDL File.aidl file in src/ Declare a single interface containing only method signatures AIDL allows using the data types: Primitive Java types (int, float, boolean, etc.) String CharSequence List (the system will use ArrayList) Map (the system will use HashMap) Collections include elements with permitted data types OSP Android Services, Lecture 4 42/55
Implementing the AIDL interface Service side YourInterface.aidl in /src Build application => generates YourInterface.java in gen/ Includes YourInterface.Stub subclass with all methods declared in the.aidl file In Service, instantiate the YourInterface.Stub and implement its methods Return Stub instance from the Service s onbind() method OSP Android Services, Lecture 4 43/55
AIDL Example - Service Side p u b l i c c l a s s R e m o t e S e r v i c e extends S e r v i c e { @ O v e r r i d e p u b l i c v o i d oncreate ( ) { s u p e r. o n C r e a t e ( ) ; @ O v e r r i d e p u b l i c I B i n d e r onbind ( I n t e n t i n t e n t ) { r e t u r n mbinder ; private f i n a l IRemoteService. Stub mbinder = new IRemoteService. Stub ( ) { p u b l i c i n t g e t P i d (){ r e t u r n P r o c e s s. mypid ( ) ; public void b a s i c T y p e s ( i n t a n I n t, long along, boolean aboolean, f l o a t afloat, double adouble, S t r i n g a S t r i n g ) { ; OSP Android Services, Lecture 4 44/55
Connecting to a Service using AIDL Client side Copy of YourInterface.aidl in src/ Create a ServiceConnection instance Within the onserviceconnected() method Use IBinder parameter Obtain reference to AIDL interface YourInterface.Stub.asInterface(IBinder) Guard calls to service methods in a try{... catch block DeadObjectException - broken connection OSP Android Services, Lecture 4 45/55
AIDL Example - Client Side IRemoteService miremoteservice ; p r i v a t e S e r v i c e C o n n e c t i o n mconnection = new S e r v i c e C o n n e c t i o n ( ) { p u b l i c v o i d onserviceconnected ( ComponentName classname, IBinder s e r v i c e ) { miremoteservice = I R e m o t e S e r v i c e. Stub. a s I n t e r f a c e ( s e r v i c e ) ; ; p u b l i c v o i d onservicedisconnected ( ComponentName classname ) { miremoteservice = n u l l ; OSP Android Services, Lecture 4 46/55
Sending Custom Objects over IPC Custom classes - implement the Parcelable interface Implement writetoparcel() Include public static final Parcelable.Creator<YourClass> CREATOR member variable Implement createfromparcel() and newarray() interface methods Create a YourClass.aidl file in which you declare the class as parcelable parcelable YourClass; OSP Android Services, Lecture 4 47/55
Example public c l a s s MyParcelable implements Pa rce lab le { private i n t mdata ; p u b l i c v o i d w r i t e T o P a r c e l ( P a r c e l out, i n t f l a g s ) { out. w r i t e I n t ( mdata ) ; p u b l i c s t a t i c f i n a l P a r c e l a b l e. C r e a t o r<myparcelable> CREATOR = new Pa rce lab le. Creator<MyParcelable >() { p u b l i c M y P a r c e l a b l e c r e a t e F r o m P a r c e l ( P a r c e l i n ) { r e t u r n new MyParcelable ( in ) ; ; p u b l i c M y P a r c e l a b l e [ ] newarray ( i n t s i z e ) { r e t u r n new M y P a r c e l a b l e [ s i z e ] ; p r i v a t e MyParcelable ( Parcel in ) { mdata = i n. r e a d I n t ( ) ; OSP Android Services, Lecture 4 48/55
Outline Overview Started Services Bound Services Messenger AIDL Foreground Services Bibliography OSP Android Services, Lecture 4 49/55
Foreground Services The user is aware of this service E.g. a music player Considered important to the user Not easily killed in low-memory situations An on-going notification while running OSP Android Services, Lecture 4 50/55
Foreground Services Started by calling startforeground(notificationid, Notification) Called from within the Service itself Specify the Activity to be started when selecting the Notification Stopped by calling stopforeground() OSP Android Services, Lecture 4 51/55
Foreground Service Example N o t i f i c a t i o n n o t i f i c a t i o n = new N o t i f i c a t i o n (R. d r a w a b l e. icon, g ettext (R. s t r i n g. t i c k e r t e x t ), System. c u r r e n t T i m e M i l l i s ( ) ) ; I n t e n t n o t i f i c a t i o n I n t e n t = new I n t e n t ( t h i s, E x a m p l e A c t i v i t y. c l a s s ) ; P e n d i n g I n t e n t p e n d i n g I n t e n t = P e n d i n g I n t e n t. g e t A c t i v i t y ( t h i s, 0, n o t i f i c a t i o n I n t e n t, 0 ) ; n o t i f i c a t i o n. s e t L a t e s t E v e n t I n f o ( t h i s, g ettext (R. s t r i n g. n o t i f i c a t i o n t i t l e ), g ettext (R. s t r i n g. n o t i f i c a t i o n m e s s a g e ), p e n d i n g I n t e n t ) ; s t a r t F o r e g r o u n d ( ONGOING NOTIFICATION ID, n o t i f i c a t i o n ) ; OSP Android Services, Lecture 4 52/55
Outline Overview Started Services Bound Services Messenger AIDL Foreground Services Bibliography OSP Android Services, Lecture 4 53/55
Bibliography http://developer.android.com/guide/components/services.html http://developer.android.com/guide/components/bound-services.html http://developer.android.com/guide/components/aidl.html http://developer.android.com/reference/android/app/service.html http: //developer.android.com/reference/android/app/intentservice.html http://developer.android.com/reference/android/content/ ServiceConnection.html http://developer.android.com/reference/android/os/messenger.html http://developer.android.com/reference/android/os/message.html OSP Android Services, Lecture 4 54/55
Keywords Android Services Started Services Foreground Services IntentService Bound Services IBinder ServiceConnection Handler Messenger Message AIDL Parcelable OSP Android Services, Lecture 4 55/55