8/10/2019 8 Services and IPC Parts 10-11-12 and 13
1/54
Douglas C. Schmidt
www.dre.vanderbilt.edu/~schmidt
Professor of Computer Science
Institute for SoftwareIntegrated Systems
Vanderbilt UniversityNashville, Tennessee, USA
Android Services & Local IPC:
Overview of Programming Bound Services
mailto:[email protected]:[email protected]8/10/2019 8 Services and IPC Parts 10-11-12 and 13
2/54
Android Services & Local IPC Douglas C. Schmidt
2
Learning Objectives in this Part of the Module Understand how to program Bound Services
public class MyService extends Service {
...
public void onCreate() {...}
protected void onDestroy() {...}
public Ibinder onBind(Intent intent) {...}
public boolean onUnbind(Intent intent) {...}
public int onStartCommand(Intent intent,
int flags,
int startId) {...}
...
}
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
3/54
Android Services & Local IPC Douglas C. Schmidt
3
Programming a Bound Service
developer.android.com/guide/components/bound-services.html
Implementing a Bound Service is
similar to a Started Service, e.g.:
Inherit from Android Serviceclass
public class MyService
extends Service {...
public void onCreate() {...}
protected void onDestroy() {...}
public IbinderonBind(Intent intent) {...}
public boolean
onUnbind(Intent intent) {...}
public int onStartCommand(Intent intent,
int flags,
int startId) {...}
...
}
http://developer.android.com/guide/components/bound-services.htmlhttp://developer.android.com/guide/components/bound-services.htmlhttp://developer.android.com/guide/components/bound-services.htmlhttp://developer.android.com/guide/components/bound-services.htmlhttp://developer.android.com/guide/components/bound-services.html8/10/2019 8 Services and IPC Parts 10-11-12 and 13
4/54
Android Services & Local IPC Douglas C. Schmidt
4
Programming a Bound Service
Implementing a Bound Service is
similar to a Started Service, e.g.:
Inherit from Android Serviceclass
Override onCreate() &onDestroy (optional)
These hook methods arecalled back by Android toinitialize & terminate aService at the appropriatetime
public class MyService
extends Service {...
public void onCreate() {...}
protected void onDestroy() {...}
public IbinderonBind(Intent intent) {...}
public boolean
onUnbind(Intent intent) {...}
public int onStartCommand(Intent intent,
int flags,
int startId) {...}
...
}
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
5/54
Android Services & Local IPC Douglas C. Schmidt
5
Programming a Bound Service
Implementing a Bound Service is
similar to a Started Service, e.g.:
Inherit from Android Serviceclass
Override onCreate() &onDestroy (optional)
Override the onBind() lifecyclemethod
Returns an Ibinder that definesa communication channel
used for two-way interaction
developer.android.com/reference/android/app/Service.html#onBind(android.content.Intent)
The object returned here istypically initialized at the
class scope or in onCreate()
public class MyService
extends Service {...
public void onCreate() {...}
protected void onDestroy() {...}
public IbinderonBind(Intent intent) {...}
public boolean
onUnbind(Intent intent) {...}
public int onStartCommand(Intent intent,
int flags,
int startId) {...}
...
}
http://developer.android.com/reference/android/app/Service.htmlonBind(android.content.Intent)http://developer.android.com/reference/android/app/Service.htmlonBind(android.content.Intent)http://developer.android.com/reference/android/app/Service.htmlonBind(android.content.Intent)http://developer.android.com/reference/android/app/Service.htmlonBind(android.content.Intent)http://developer.android.com/reference/android/app/Service.htmlonBind(android.content.Intent)8/10/2019 8 Services and IPC Parts 10-11-12 and 13
6/54
Android Services & Local IPC Douglas C. Schmidt
6
developer.android.com/reference/android/app/Service.html#onUnbind(android.content.Intent)
Programming a Bound Service
Implementing a Bound Service is
similar to a Started Service, e.g.:
Inherit from Android Serviceclass
Override onCreate() &onDestroy (optional)
Override the onBind() lifecyclemethod
Can also implement onUnbind()
Called when all clients have
disconnected from a particularinterface published by theService by callingunBindService()
public class MyService
extends Service {...
public void onCreate() {...}
protected void onDestroy() {...}
public IbinderonBind(Intent intent) {...}
public boolean
onUnbind(Intent intent) {...}
public int onStartCommand(Intent intent,
int flags,
int startId) {...}
...
}
http://developer.android.com/reference/android/app/Service.htmlonUnbind(android.content.Intent)http://developer.android.com/reference/android/app/Service.htmlonUnbind(android.content.Intent)http://developer.android.com/reference/android/app/Service.htmlonUnbind(android.content.Intent)http://developer.android.com/reference/android/app/Service.htmlonUnbind(android.content.Intent)http://developer.android.com/reference/android/app/Service.htmlonUnbind(android.content.Intent)8/10/2019 8 Services and IPC Parts 10-11-12 and 13
7/54
Android Services & Local IPC Douglas C. Schmidt
7developer.android.com/guide/components/bound-services.html#Lifecycle
Programming a Bound Service
Implementing a Bound Service is
similar to a Started Service, e.g.:
Inherit from Android Serviceclass
Override onCreate() &onDestroy (optional)
Override the onBind() lifecyclemethod
Can also implement onUnbind()
Called when all clients have
disconnected from a particularinterface published by the service
Typically returns false, but canreturn true to trigger reBind()
public class MyService
extends Service {...
public void onCreate() {...}
protected void onDestroy() {...}
public IbinderonBind(Intent intent) {...}
public boolean
onUnbind(Intent intent) {...}
public int onStartCommand(Intent intent,
int flags,
int startId) {...}
...
}
http://developer.android.com/guide/components/bound-services.html#Lifecyclehttp://developer.android.com/guide/components/bound-services.html#Lifecyclehttp://developer.android.com/guide/components/bound-services.html#Lifecycle8/10/2019 8 Services and IPC Parts 10-11-12 and 13
8/54
Android Services & Local IPC Douglas C. Schmidt
8
Programming a Bound Service
Implementing a Bound Service is
similar to a Started Service, e.g.:
Inherit from Android Serviceclass
Override onCreate() &onDestroy (optional)
Override the onBind() lifecyclemethod
Can also implement onUnbind()
onStartCommand() is typically not
implemented for a Bound Service Only do this if you want to
manage the lifecycle of theBound Service
developer.android.com/guide/components/bound-services.html#Lifecycle
public class MyService
extends Service {...
public void onCreate() {...}
protected void onDestroy() {...}
public IbinderonBind(Intent intent) {...}
public boolean
onUnbind(Intent intent) {...}
public int onStartCommand(Intent intent,
int flags,
int startId) {...}
...
}
http://developer.android.com/guide/components/bound-services.html#Lifecyclehttp://developer.android.com/guide/components/bound-services.html#Lifecyclehttp://developer.android.com/guide/components/bound-services.html#Lifecycle8/10/2019 8 Services and IPC Parts 10-11-12 and 13
9/54
Android Services & Local IPC Douglas C. Schmidt
9
Implementing a Bound Service is
similar to a Started Service, e.g.:
Inherit from Android Serviceclass
Override onCreate() &onDestroy (optional)
Override the onBind() lifecyclemethod
Can also implement onUnbind()
onStartCommand() is typically not
implemented for a Bound Service Include the Service in theAndroidManifest.xml config file
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
10/54
Android Services & Local IPC Douglas C. Schmidt
10
Programming two-way communication with Bound
Services is straightforward The bulk of the implementations are handled byAndroid & a client-side callback protocol
Summary
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
11/54
Android Services & Local IPC Douglas C. Schmidt
11
Programming two-way communication with Bound
Services is straightforward One of the most important parts of implementing a
Bound Service is defining the interface that theonBind() callback method returns
Three common ways to implement the Service's
IBinder interface are discussed next Extent the Binder class
Use a Messenger
Use the Android Interface DefinitionLanguage (AIDL)
Summary
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
12/54
Douglas C. Schmidt
[email protected]/~schmidt
Professor of Computer Science
Institute for SoftwareIntegrated Systems
Vanderbilt UniversityNashville, Tennessee, USA
Android Services & Local IPC:
Local Bound Service Communication
by Extending the Binder Class
mailto:[email protected]:[email protected]8/10/2019 8 Services and IPC Parts 10-11-12 and 13
13/54
Android Services & Local IPC Douglas C. Schmidt
13
Learning Objectives in this Part of the Module
Understand how to communicate with Local Bound Services by extending
the Binder class
onStart()
getRand()
ServiceConnection
Single Process
onServiceConnected()
Return reference
to object that
implements the
IBinder interface
Dispatch callback
Assign
todatamem
ber
Dispatch method
& return result
mBinder
mServiceLocalBinder
Call getRand()
getService()
bindService()
2
Start Bound
Service process
if its not already
running
4
Call getService()5
6
Intent
1
onBind()
3
7
BindingActivity LocalService
8
See developer.android.com/guide/components/bound-services.html#Binder
http://developer.android.com/guide/components/bound-services.html#Binderhttp://developer.android.com/guide/components/bound-services.html#Binderhttp://developer.android.com/guide/components/bound-services.html#Binder8/10/2019 8 Services and IPC Parts 10-11-12 and 13
14/54
Android Services & Local IPC Douglas C. Schmidt
14
Communication via a Local Binder
Sometimes a Bound Service is used only by a local client Activity & need not
work across processes In this collocated case, simply implement an instance of a Binder subclass
that provides the client direct access to public methods in a Service
onStart()
getRand()
Single Process
onServiceConnected() mBinder
mService
getService()
onBind()ServiceConnection
LocalBinder
BindingActivity LocalService
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
15/54
Android Services & Local IPC Douglas C. Schmidt
15
onStart()
getRand()
ServiceConnection
Single Process
mBinder
mServiceLocalBinder
getService()
2
Start Bound
Service process
if its not already
running
Intent
onBind()
Communication via a Local BinderThe onBind() method can create a Binder object that either:
Contains public methods the client can call Returns current Service instance, which has public methods the client can call, or
Returns an instance of another class hosted by Service that the client can call
bindService()
1
BindingActivity LocalService
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
16/54
Android Services & Local IPC Douglas C. Schmidt
16
onStart()
getRand()
ServiceConnection
Single Process
onServiceConnected()
Return reference
to object that
implements the
IBinder interface
Dispatch callbackmBinder
mServiceLocalBinder
getService()
4
onBind()
3
Communication via a Local BinderThe LocalBinder is a Binder
public class LocalBinder extends Binder {...
}
BindingActivity LocalService
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
17/54
Android Services & Local IPC Douglas C. Schmidt
17
onStart()
getRand()
ServiceConnection
Single Process
onServiceConnected()
Return reference
to object that
implements the
IBinder interface
Assign
todatamember
Dispatch method
& return result
mBinder
mServiceLocalBinder
getService()
Call getService()5
6
onBind()
7
Communication via a Local Binder
BindingActivity LocalService
The getService() factory method allows clients to call LocalService methods
public class LocalBinder extends Binder {LocalService getService() { return LocalService.this; }
}
d d l l h d
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
18/54
Android Services & Local IPC Douglas C. Schmidt
18
onStart()
BindingActivity
getRand()
ServiceConnection
LocalService
Single Process
onServiceConnected() mBinder
mServiceLocalBinder
Call getRand()
getService()
onBind()
Communication via a Local Binder
getRand() is a two-way method call thatreturns a random number to the caller
8
A d id S i & L l IPC D l C S h id
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
19/54
Android Services & Local IPC Douglas C. Schmidt
19
Example of Service that Extends the Binder
public class LocalService extends Service {
public class LocalBinder extends Binder
{ LocalService getService() { return LocalService.this; } }
private final IBinder mBinder = new LocalBinder ();
public IBinder onBind(Intent intent) { return mBinder; }
private final Random mGenerator = new Random();
public int getRand() { return mGenerator.nextInt(100); }
}
Return Serviceinstance to client
Called by Android when client invokesbindService() to return Binder instance
Factory Method for clients
Create a Binder object that returns the current Service instance, which has
public methods the client can call
Called by clients to generatea random number
A d id S i & L l IPC D l C S h idt
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
20/54
Android Services & Local IPC Douglas C. Schmidt
20
public class BindingActivity extends Activity {
LocalService mService; boolean mBound = false;
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, LocalService.class);
bindService(intent, mConn, Context.BIND_AUTO_CREATE);
}
protected void onStop() {
super.onStop();if (mBound) { unbindService(mConn); mBound = false; }
}
public void onButtonClick(View v) {if (mBound) Toast.makeText(this, mService.getRand(),
Toast.LENGTH_SHORT).show();}
Example of Client that Uses the Extended Binder
Objectstate
Bind to LocalService
The client receive the Binder from the onServiceConnected() callback method
& makes calls to the Bound Service using the provided methods
Unbind to LocalService
Calls Services method
A d id S i & L l IPC D l C S h idt
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
21/54
Android Services & Local IPC Douglas C. Schmidt
21
public class BindingActivity extends Activity {...
private ServiceConnection mConn = new ServiceConnection() {
public void onServiceConnected(ComponentName className,IBinder service) {
LocalService.LocalBinder binder =(LocalService.LocalBinder)service;
mService = binder.getService(); mBound = true;}
public void onServiceDisconnected(ComponentName a){ mBound = false; }
};}
The client receive the Binder from the onServiceConnected() callback method
& makes calls to the Bound Service using the provided methods
Defines Service binding callbacks, passed to bindService()
Cast the IBinder & get LocalService instance
Example of Client that Uses the Extended Binder
Called when Service is unexpectedly disconnected
A d id S i & L l IPC D l C S h idt
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
22/54
Android Services & Local IPC Douglas C. Schmidt
22
Summary
Using Local Binders is the preferred technique when a Service is merely a
background worker for an Activity The Service & the client must be in the same process because this
technique does not perform any (de)marshaling across processes
onStart()
getRand()
ServiceConnection
Single Process
onServiceConnected()
Return reference
to object thatimplements the
IBinder interface
Dispatch callback
Assign
todatamember
Dispatch method
& return result
mBinder
mServiceLocalBinder
Call getRand()
getService()
bindService()
2
Start Bound
Service process
if its not alreadyrunning
4
Call getService() 5
6
Intent
1
onBind()
3
7
BindingActivity LocalService
8
And oid Se i e & Lo l IPC Do gl C S hmidt
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
23/54
Android Services & Local IPC Douglas C. Schmidt
23
Using Local Binders is the preferred technique when a Service is merely a
background worker for an Activity The only reason not to create a Bound Service this way is because the
Service is used by other Apps or across separate processes
Note how the method is dispatched in the same thread as the caller
Summary
onStart()
getRand()
ServiceConnection
Single Process
onServiceConnected()
Return reference
to object thatimplements the
IBinder interface
Dispatch callback
Assign
todatamember
Dispatch method
& return result
mBinder
mServiceLocalBinder
Call getRand()
getService()
bindService()
2
Start Bound
Service process
if its not alreadyrunning
4
Call getService() 5
6
Intent
1
onBind()
3
7
BindingActivity LocalService
8
A d id S i L l IPC
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
24/54
Douglas C. Schmidt
[email protected]/~schmidt
Professor of Computer Science
Institute for SoftwareIntegrated Systems
Vanderbilt UniversityNashville, Tennessee, USA
Android Services & Local IPC:
Bound Service Communication
Via Messengers
Android Services & Local IPC Douglas C Schmidt
mailto:[email protected]:[email protected]8/10/2019 8 Services and IPC Parts 10-11-12 and 13
25/54
Android Services & Local IPC Douglas C. Schmidt
25
Learning Objectives in this Part of the Module
Understand how to communicate with Bound Services via Messengers
Single Process
MessengerActivity
handleMessage()
ServiceConnection
MessengerService
InHandler
onServiceConnected()
bindService()
mSvcMsg
Return
reference to
mMessenger
onBind()
DispatchhandleMessage()
mMessenger
Dispatch callback
CreateMesse
nger&
assigntodata
member
Call send() to pass a
Message to Service
1
2
6
7
3
5
Start Bound Service
process if its not
already running
Intent
onStart()
4
developer.android.com/guide/components/bound-services.html#Messenger
Android Services & Local IPC Douglas C Schmidt
http://developer.android.com/guide/components/bound-services.html#Messengerhttp://developer.android.com/guide/components/bound-services.html#Messengerhttp://developer.android.com/guide/components/bound-services.html#Messenger8/10/2019 8 Services and IPC Parts 10-11-12 and 13
26/54
Android Services & Local IPC Douglas C. Schmidt
26
Using a Messenger in a Bound Service
A Messenger can be used to communicate with a Bound Service
Enables interaction between an Activity & a Bound Service without usingAIDL (which is more powerful & complicated)
Generalizing to communicate between processes is relatively straightforward
Single Process
MessengerActivity
handleMessage()
ServiceConnection
MessengerService
InHandler
onServiceConnected()
mSvcMsg
onBind()
mMessenger
onStart()
Android Services & Local IPC Douglas C Schmidt
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
27/54
Android Services & Local IPC Douglas C. Schmidt
27
Using a Messenger in a Bound Service
Single Process
MessengerActivity
handleMessage()
ServiceConnection
MessengerService
InHandler
onServiceConnected()
bindService()
mSvcMsg
onBind()
mMessenger
1
2
Start Bound Service
process if its not
already running
Intent
onStart()
Implement a Handler that receives a callback for each callfrom a client & reference the Handler in a Messenger object
Android Services & Local IPC Douglas C Schmidt
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
28/54
Android Services & Local IPC Douglas C. Schmidt
28
Using a Messenger in a Bound Service
Single Process
MessengerActivity
handleMessage()
ServiceConnection
MessengerService
InHandler
onServiceConnected()
mSvcMsg
Return
reference to
mMessenger
onBind()
mMessenger
Dispatch callback
CreateMessenger&
as
signtodatamember
3
5
onStart()
4
Messenger creates IBinder that Service returns to clients from onBind()
public IBinder onBind(Intent intent){ returnmMessenger.getBinder(); }
developer.android.com/reference/android/os/Messenger.html#getBinder()
http://developer.android.com/reference/android/os/Messenger.htmlgetBinder()http://developer.android.com/reference/android/os/Messenger.htmlgetBinder()http://developer.android.com/reference/android/os/Messenger.htmlgetBinder()8/10/2019 8 Services and IPC Parts 10-11-12 and 13
29/54
Android Services & Local IPC Douglas C Schmidt
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
30/54
Android Services & Local IPC Douglas C. Schmidt
30
public class MessengerService extends Service {
static final int MSG_PERFORM_ACTION = 1;
class InHandler extends Handler {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_PERFORM_ACTION:
processMessage(msg); break;default: super.handleMessage(msg);
}
}
}
final Messenger mMessenger = new Messenger(new InHandler());
public IBinder onBind(Intent intent)
{ return mMessenger.getBinder(); }
}
Example Using a Messenger in a Bound Service
Instruct Serviceto do some action
Handler for incomingclient Messages
Target for clients to send Messages to InHandler
Return Ibinder so clients can send Messages to Service
developer.android.com/reference/android/os/Messenger.html#Messen er android.os.Handler
Android Services & Local IPC Douglas C Schmidt
http://developer.android.com/reference/android/os/Messenger.htmlMessenger(android.os.IBinder)http://developer.android.com/reference/android/os/Messenger.htmlMessenger(android.os.IBinder)http://developer.android.com/reference/android/os/Messenger.htmlMessenger(android.os.IBinder)http://developer.android.com/reference/android/os/Messenger.htmlMessenger(android.os.IBinder)http://developer.android.com/reference/android/os/Messenger.htmlMessenger(android.os.IBinder)8/10/2019 8 Services and IPC Parts 10-11-12 and 13
31/54
Android Services & Local IPC Douglas C. Schmidt
31
public class MessengerActivity extends Activity {
...
Messenger mSvcMsg = null;
boolean mBound;
private ServiceConnection mConnection =
new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
mSvcMsg = new Messenger(service); mBound = true;
}
public void onServiceDisconnected(ComponentName className) {
mSvcMsg = null; mBound = false;
}
};
Example Using a Messenger in an Activity
Means to communicate w/Service
Flag indicating if Service is bound
Called when connection with Service has been established,
giving the object to interact with the Service
Called when Service is unexpectedly disconnected
developer.android.com/reference/android/os/Messenger.html#Messen er android.os.IBinder
Android Services & Local IPC Douglas C Schmidt
http://developer.android.com/reference/android/os/Messenger.htmlMessenger(android.os.IBinder)http://developer.android.com/reference/android/os/Messenger.htmlMessenger(android.os.IBinder)http://developer.android.com/reference/android/os/Messenger.htmlMessenger(android.os.IBinder)http://developer.android.com/reference/android/os/Messenger.htmlMessenger(android.os.IBinder)http://developer.android.com/reference/android/os/Messenger.htmlMessenger(android.os.IBinder)8/10/2019 8 Services and IPC Parts 10-11-12 and 13
32/54
Android Services & Local IPC Douglas C. Schmidt
32
public class MessengerActivity extends Activity {
...
protected void onStart() {super.onStart();
bindService(new Intent(this, MessengerService.class),
mConnection, Context.BIND_AUTO_CREATE);
}
protected void onStop() {
super.onStop();
if (mBound) { unbindService(mConnection); mBound = false; }
}
public void onButtonClick(View v) {
if (!mBound) return;
Message msg = Message.obtain
(null, MessengerService.MSG_PERFORM_ACTION, 0, 0);
...
mSvcMsg.send(msg);
}
...
Create & send a Message to Messengerin Service, using a 'what' value
Example Using a Messenger in an Activity
Bind to the service
Unbind from the service
Android Services & Local IPC Douglas C Schmidt
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
33/54
Android Services & Local IPC Douglas C. Schmidt
33
Using Messengers for Two-way Communication
Two-way communication via Messengers in a Bound Service is a slight
variation on the approach described earlier It involves sending a replyMessenger with the original Message, which is
then used to call send() back on the client
We didnt show the code for two-way communication in our example
Single Process
MessengerActivity MessengerService
InHandler
mSvcMsg
onBind()
Dispatch
handleMessage()
mMessenger6
7
onStart()
Call send() to pass
Message to Service,
including another
Messenger for the
reply path
Dispatch reply
handleMessage()
ReplyHandler
8 handleMessage()
Android Services & Local IPC Douglas C Schmidt
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
34/54
Android Services & Local IPC Douglas C. Schmidt
34
Summary If an Activity needs to communicate with a Bound Service a Messenger can
provide a message-passing interface for this Service
This technique makes it easy to perform inter-process communication (IPC)without the need to use AIDL
Single Process
MessengerActivity
handleMessage()
ServiceConnection
MessengerService
InHandler
onServiceConnected()
bindService()
mSvcMsg
Return
reference to
mMessenger
onBind()
Dispatch
handleMessage()
mMessenger
Dispatch callback
Crea
teMessenger&
assigntodatamember
Call send() to pass
Message to Service
1
2
6
7
3
5
Start Bound Service
process if its not
already running
Intent
onStart()
4
Some additional programming is required to use Messengers for IPC
Android Services & Local IPC Douglas C. Schmidt
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
35/54
Android Services & Local IPC Douglas C. Schmidt
35
Summary If an Activity needs to communicate with a Bound Service a Messenger can
provide a message-passing interface for this Service
A Messenger queues the incoming send() calls, which allows the Service tohandle one call at a time without requiring thread-safe programming
Single Process
MessengerActivity
handleMessage()
ServiceConnection
MessengerService
InHandler
onServiceConnected()
bindService()
mSvcMsg
Return
reference to
mMessenger
onBind()
Dispatch
handleMessage()
mMessenger
Dispatch callback
Crea
teMessenger&
assigntodatamember
Call send() to pass
Message to Service
1
2
6
7
3
5
Start Bound Service
process if its not
already running
Intent
onStart()
4
If your Service must be multi-threaded then youll need AIDL (covered next)
Android Services & Local IPC
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
36/54
Douglas C. Schmidt
[email protected]/~schmidt
Professor of Computer Science
Institute for SoftwareIntegrated Systems
Vanderbilt UniversityNashville, Tennessee, USA
Android Services & Local IPC:
Advanced Bound Service Communication
Overview of the AIDL & Binder RPC
Android Services & Local IPC Douglas C. Schmidt
mailto:[email protected]:[email protected]8/10/2019 8 Services and IPC Parts 10-11-12 and 13
37/54
Android Services & Local IPC Douglas C. Schmidt
37
Learning Objectives in this Part of the Module
Understand AIDL & Binder RPC mechanisms for communicating with Bound
ServicesBinder IPCMechanism
DownloadActivity
downloadImage()
ServiceConnection
DownloadService
Process A Process B
ImageBinder
Return refto Binderobject
Dispatch callbackAssignProxytodatam
ember
Stub dispatches
method & returns
result
1
2
3
5
mBinder
onServiceConnected()
onBind()
mBoundService
onStart()
Start Bound Service
process if its not
already running
Intent
bindService()
initiateDownload()
downloadImage()
7
6
4
AIDL & Binder RPC are the most powerful Android local IPC mechanism
Android Services & Local IPC Douglas C. Schmidt
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
38/54
d o d Se ces & oca C oug as C Sc dt
38
downloadImage()
ImageBinder
Motivation for AIDL & Binder RPC One process on Android cannot normally access the address space of another
process Our two previous examples of communicating with Bound Services side-
stepped this issue by collocating the Activity & the Service in the sameprocess address space
Client Process Server Process
DownloadActivity DownloadService
mBoundService
Android Services & Local IPC Douglas C. Schmidt
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
39/54
g
39
Motivation for AIDL & Binder RPC One process on Android cannot normally access the address space of another
process To communicate therefore they need to decompose their objects into
primitives that the operating system can understand & (de)marshal theobjects across the process boundary
Marshaling converts data from native format into a linearized format
DownloadActivity DownloadService
1
downloadImage()mBoundService
ImageBinder
Client Process Server Process
en.wikipedia.org/wiki/Marshalling_(computer_science)has more info
Android Services & Local IPC Douglas C. Schmidt
http://en.wikipedia.org/wiki/Marshalling_(computer_science)http://en.wikipedia.org/wiki/Marshalling_(computer_science)http://en.wikipedia.org/wiki/Marshalling_(computer_science)8/10/2019 8 Services and IPC Parts 10-11-12 and 13
40/54
g
40
Motivation for AIDL & Binder RPC One process on Android cannot normally access the address space of another
process To communicate therefore they need to decompose their objects into
primitives that the operating system can understand & (de)marshal theobjects across the process boundary
Marshaling converts data from native format into a linearized format
Demarshaling converts data from the linearized format into native format
DownloadActivity DownloadService
2
downloadImage()mBoundService
ImageBinder
Client Process Server Process
en.wikipedia.org/wiki/Marshalling_(computer_science)has more info
Android Services & Local IPC Douglas C. Schmidt
http://en.wikipedia.org/wiki/Marshalling_(computer_science)http://en.wikipedia.org/wiki/Marshalling_(computer_science)http://en.wikipedia.org/wiki/Marshalling_(computer_science)8/10/2019 8 Services and IPC Parts 10-11-12 and 13
41/54
g
41
Motivation for AIDL & Binder RPC One process on Android cannot normally access the address space of another
process To communicate therefore they need to decompose their objects into
primitives that the operating system can understand & (de)marshal theobjects across the process boundary
The code to (de)marshal is tedious to write, so Android automates it with the
Android Interface Definition Language (AIDL) & an associated compiler AIDL is similar to Java interfaces
downloadImage()
ImageBinder
DownloadActivity DownloadService
interface IDownload {
String downloadImage
(String uri);}
Client Process Server Process
mBoundService
Android Services & Local IPC Douglas C. Schmidt
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
42/54
g
42
Motivation for AIDL & Binder RPC One process on Android cannot normally access the address space of another
process To communicate therefore they need to decompose their objects into
primitives that the operating system can understand & (de)marshal theobjects across the process boundary
The code to (de)marshal is tedious to write, so Android automates it with the
Android Interface Definition Language (AIDL) & an associated compiler AIDL is similar to Java interfaces
Compilation is handled automatically by Eclipse
downloadImage()
ImageBinder
DownloadActivity DownloadService
interface IDownload {
String downloadImage
(String uri);}
developer.android.com/guide/components/aidl.htmlhas AIDL overview
MyService.Stub
Client Process Server Process
mBoundService
MyService.Stub.Proxy AIDL Compiler
Android Services & Local IPC Douglas C. Schmidt
http://developer.android.com/guide/components/aidl.htmlhttp://developer.android.com/guide/components/aidl.htmlhttp://developer.android.com/guide/components/aidl.html8/10/2019 8 Services and IPC Parts 10-11-12 and 13
43/54
g
43
Motivation for AIDL & Binder RPC One process on Android cannot normally access the address space of another
process To communicate therefore they need to decompose their objects into
primitives that the operating system can understand & (de)marshal theobjects across the process boundary
The code to (de)marshal is tedious to write, so Android automates it with the
Android Interface Definition Language (AIDL) & an associated compiler The Android Binder provides a local RPC mechanism for cross-process calls
Apps rarely access the Binder directly, but instead use AIDL Stubs & Proxies
DownloadActivity DownloadService
downloadImage()
ImageBinder
MyService.Stub
Client Process Server Process
mBoundService
MyService.Stub.Proxy
Call method downloadImage()
Return results to caller
1
2
Binder IPC Mechanism
elinux.org/Android_Binderhas more info on Android Binder RPC
Android Services & Local IPC Douglas C. Schmidt
http://elinux.org/Android_Binderhttp://elinux.org/Android_Binder8/10/2019 8 Services and IPC Parts 10-11-12 and 13
44/54
44
Details of Android Binder & AIDL IPC The Binder Driver is installed in the Linux kernel to accelerate IPC
It uses shared memory & per-process thread pool for high performance
Call method downloadImage()
Return results to caller
1
2
Binder IPC MechanismDownloadActivity DownloadService
downloadImage()
ImageBinder
MyService.Stub
Client Process Server Process
mBoundService
MyService.Stub.Proxy
Android Services & Local IPC Douglas C. Schmidt
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
45/54
45
Call method downloadImage()
Return results to caller
1
2
Binder IPC MechanismDownloadActivity
Client Process
mBoundService
MyService.Stub.Proxy
Details of Android Binder & AIDL IPC The Binder Driver is installed in the Linux kernel to accelerate IPC
Android (system) Services can be written in C/C++, as well as Java
sites.google.com/site/io/anatomy--physiology-of-an-androidhas more info
downloadImage()
C/C++ code
NDKDownloadService
Server Process
NDKService::Stub
Android Services & Local IPC Douglas C. Schmidt
https://sites.google.com/site/io/anatomy--physiology-of-an-androidhttps://sites.google.com/site/io/anatomy--physiology-of-an-androidhttps://sites.google.com/site/io/anatomy--physiology-of-an-android8/10/2019 8 Services and IPC Parts 10-11-12 and 13
46/54
46
Details of Android Binder & AIDL IPC The Binder Driver is installed in the Linux kernel to accelerate IPC
Android (system) Services can be written in C/C++, as well as Java Callers data is marshaled into parcels, copied to callees process, &
demarshaled into what callee expects
Call method downloadImage()
Return results to caller
1
2
Binder IPC MechanismDownloadActivity DownloadService
downloadImage()
ImageBinder
MyService.Stub
Client Process Server Process
mBoundService
MyService.Stub.Proxy
Android Services & Local IPC Douglas C. Schmidt
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
47/54
47
Details of Android Binder & AIDL IPC The Binder Driver is installed in the Linux kernel to accelerate IPC
Android (system) Services can be written in C/C++, as well as Java Callers data is marshaled into parcels, copied to callees process, &
demarshaled into what callee expects
Two-way method invocations are synchronous (block the caller)
One-way method invocations do not block the caller
Call method downloadImage()
Return results to caller
1
2
Binder IPC MechanismDownloadActivity DownloadService
downloadImage()
ImageBinder
MyService.Stub
Client Process Server Process
mBoundService
MyService.Stub.Proxy
Caller thread blocks waiting for results from the Service
Android Services & Local IPC Douglas C. Schmidt
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
48/54
48
Details of Android Binder & AIDL IPC The Binder Driver is installed in the Linux kernel to accelerate IPC
Android (system) Services can be written in C/C++, as well as Java Callers data is marshaled into parcels, copied to callees process, &
demarshaled into what callee expects
Two-way method invocations are synchronous (block the caller)
Android also supports asynchronous calls between processes
Implemented using one-way methods & callback objects
1
Binder IPC MechanismDownloadActivity DownloadService
Client Process Server Process
Client passes callback object via oneway method to Service
setCallback()
ImageBindermBoundService
Call oneway method setCallback()
ReplyHandler
Android Services & Local IPC Douglas C. Schmidt
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
49/54
49
Details of Android Binder & AIDL IPC The Binder Driver is installed in the Linux kernel to accelerate IPC
Android (system) Services can be written in C/C++, as well as Java Callers data is marshaled into parcels, copied to callees process, &
demarshaled into what callee expects
Two-way method invocations are synchronous (block the caller)
Android also supports asynchronous calls between processes
Implemented using one-way methods & callback objects
Binder IPC MechanismDownloadActivity DownloadService
Client Process Server Process
Caller thread doesnt block waiting for results
ImageBinder
setCallback()mBoundService
ReplyHandler
1 Call oneway method setCallback()
Android Services & Local IPC Douglas C. Schmidt
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
50/54
50
Details of Android Binder & AIDL IPC The Binder Driver is installed in the Linux kernel to accelerate IPC
Android (system) Services can be written in C/C++, as well as Java Callers data is marshaled into parcels, copied to callees process, &
demarshaled into what callee expects
Two-way method invocations are synchronous (block the caller)
Android also supports asynchronous calls between processes
Implemented using one-way methods & callback objects
2
Binder IPC MechanismDownloadActivity DownloadService
Client Process Server Process
downloadCallback()
ImageBinder
Service invokes a one-way method to return results
Call oneway method sendPath()
mBoundService
ReplyHandler
sendPath()
Android Services & Local IPC Douglas C. Schmidt
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
51/54
51
Details of Android Binder & AIDL IPC The Binder Driver is installed in the Linux kernel to accelerate IPC
Android (system) Services can be written in C/C++, as well as Java Callers data is marshaled into parcels, copied to callees process, &
demarshaled into what callee expects
Two-way method invocations are synchronous (block the caller)
Android also supports asynchronous calls between processes via callbacks
Server typically handles one- & two-way method invocations in a thread pool
Service objects & methods must therefore be thread-safe
Call method downloadImage()
Return results to caller
1
2
Binder IPC MechanismDownloadActivity DownloadService
downloadImage()
ImageBinder
MyService.Stub
Client Process Server Process
mBoundService
MyService.Stub.Proxy
Android Services & Local IPC Douglas C. Schmidt
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
52/54
52
Summary
www.vogella.com/tutorials.html
There are many Android tutorials & resources available online
Android provides a wide range of local IPC mechanisms for communicating
with Bound Services
http://www.vogella.com/tutorials.htmlhttp://www.vogella.com/tutorials.html8/10/2019 8 Services and IPC Parts 10-11-12 and 13
53/54
Android Services & Local IPC Douglas C. Schmidt
8/10/2019 8 Services and IPC Parts 10-11-12 and 13
54/54
Summary
Android provides a wide range of local IPC mechanisms for communicating
with Bound Services AIDL is a language for defining Binder-based interfaces to Bound Services
Its used with the Binder RPC mechanism to implement the Brokerpattern
Many other patterns are used to implement AIDL & Binder RPC
e.g., Proxy,Adapter,Activator, etc.
Process Boundary