Android Services & Local IPC: Overview of Programming Bound Services

Similar documents
Android Services & Local IPC: The Command Processor Pattern (Part 1)

Services & Interprocess Communication (IPC) CS 282 Principles of Operating Systems II Systems Programming for Android

Services. Marco Ronchetti Università degli Studi di Trento

Services. Marco Ronchetti Università degli Studi di Trento

Broadcast receivers. Marco Ronchetti Università degli Studi di Trento

Android Services & Local IPC: The Activator Pattern (Part 2)

EMBEDDED SYSTEMS PROGRAMMING Android Services

Android. Broadcasts Services Notifications

Android Fundamentals - Part 1

Services. Background operating component without a visual interface Running in the background indefinitely

Overview of Activities

Implementing a Download Background Service

Services Broadcast Receivers Permissions

Android System Development Day-4. Team Emertxe

Android Architecture and Binder. Dhinakaran Pandiyan Saketh Paranjape

Programming with Android: Notifications, Threads, Services. Luca Bedogni. Dipartimento di Scienze dell Informazione Università di Bologna

Termite WiFi Direct API

Mobile Programming Practice Background processing AsynTask Service Broadcast receiver Lab #5

Services are software components designed specifically to perform long background operations.

MOBILE APPLICATION DEVELOPMENT LECTURE 10 SERVICES IMRAN IHSAN ASSISTANT PROFESSOR

CS378 -Mobile Computing. Services and Broadcast Receivers

Services. service: A background task used by an app.

Software Practice 3 Today s lecture Today s Task

ANDROID SERVICES, BROADCAST RECEIVER, APPLICATION RESOURCES AND PROCESS

Summarizing Control Flow of Callbacks for Android API Methods

Understand applications and their components. activity service broadcast receiver content provider intent AndroidManifest.xml

Infrastructure Middleware (Part 1): Hardware Abstraction Layer (HAL)

Extended Atomicity Checking with Blame Assignment for Android Applications

Embedded Systems Programming - PA8001

Mobile Platforms and Middleware

CHAPTER - 4 REMOTE COMMUNICATION

Overview of Java Threads (Part 3)

Overview of Java s Support for Polymorphism

The Java ExecutorService (Part 1)

Notifications and Services. Landon Cox March 28, 2017

Overview of Java Threads (Part 2)

Communication. Distributed Systems Santa Clara University 2016

The Java FutureTask. Douglas C. Schmidt

CSci Introduction to Distributed Systems. Communication: RPC

Remote Objects and RMI

Activities. Repo:

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar

Outline. Interprocess Communication. Interprocess Communication. Communication Models: Message Passing and shared Memory.

Benefits of Concurrency in Java & Android: Program Structure

UNDERSTANDING ACTIVITIES

Mobile Computing. Introduction to Android

Generating Predicate Callback Summaries for the Android Framework

Mobile Programming Lecture 9. Bound Services, Location, Sensors, IntentFilter

Java Semaphore (Part 1)

Lifecycle Callbacks and Intents

Infrastructure Middleware (Part 3): Android Runtime Core & Native Libraries

Upcoming Assignments Quiz Friday? Lab 5 due today Alpha Version due Friday, February 26

IPC 的 Proxy-Stub 设计模式 (b)

Contents. Java RMI. Java RMI. Java RMI system elements. Example application processes/machines Client machine Process/Application A

Java Monitor Objects: Synchronization (Part 1)

COLLEGE OF ENGINEERING, NASHIK-4

CS378 - Mobile Computing. Anatomy of an Android App and the App Lifecycle

The Java Executor (Part 1)

Verteilte Systeme (Distributed Systems)

Java 8 Parallel ImageStreamGang Example (Part 3)

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

IBD Intergiciels et Bases de Données

Efficient Android Threading

CS 370 Android Basics D R. M I C H A E L J. R E A L E F A L L

Thread. A Thread is a concurrent unit of execution. The thread has its own call stack for methods being invoked, their arguments and local variables.

Writing Efficient Drive Apps for Android. Claudio Cherubino / Alain Vongsouvanh Google Drive Developer Relations

2017 Pearson Educa2on, Inc., Hoboken, NJ. All rights reserved.

CS 5523 Operating Systems: Remote Objects and RMI

JAVA RMI. Remote Method Invocation

shared objects monitors run() Runnable start()

Amandroid: A Precise and General Inter-component Data Flow Analysis Framework for Security Vetting of Android Apps

Overview of Patterns: Introduction

Slides on cross- domain call and Remote Procedure Call (RPC)

PATTERN-ORIENTED SOFTWARE ARCHITECTURE

Lifecycle-Aware Components Live Data ViewModel Room Library

Activities and Fragments

Overview of Advanced Java 8 CompletableFuture Features (Part 3)

Distributed Systems Theory 4. Remote Procedure Call. October 17, 2008

Android Services. Victor Matos Cleveland State University. Services

Minds-on: Android. Session 2

Android. Mobile operating system developed by Google A complete stack. Based on the Linux kernel Open source under the Apache 2 license

Android. Michael Greifeneder. Image source: Android homepage

Message Passing vs. Distributed Objects. 5/15/2009 Distributed Computing, M. L. Liu 1

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring Lecture 22: Remote Procedure Call (RPC)

COPYRIGHTED MATERIAL. Table of Contents. Foreword... xv. About This Book... xvii. About The Authors... xxiii. Guide To The Reader...

CS555: Distributed Systems [Fall 2017] Dept. Of Computer Science, Colorado State University

Software Architecture Patterns

Lecture 5: Object Interaction: RMI and RPC

Lecture 1 - Introduction to Android

Android Ecosystem and. Revised v4presenter. What s New

Today CSCI Remote Method Invocation (RMI) Distributed Objects

Distributed Objects SPL/ SPL 201 / 0 1

INTRODUCTION TO ANDROID

PENGEMBANGAN APLIKASI PERANGKAT BERGERAK (MOBILE)

IPN-ESCOM Application Development for Mobile Devices. Extraordinary. A Web service, invoking the SOAP protocol, in an Android application.

C++ Inheritance and Encapsulation

Android Activities. Akhilesh Tyagi

5.4. Events and notifications

A Case Study of Gang of Four (GoF) Patterns : Part 7

Mobile Application Development Android

Transcription:

: Overview of Programming Bound Services d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Professor of Computer Science Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA

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) {...}... 2

Programming a Bound Service Implementing a Bound Service is similar to a Started Service, e.g.: Inherit from Android Service class 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) {...}... developer.android.com/guide/components/bound-services.html 3

Programming a Bound Service Implementing a Bound Service is similar to a Started Service, e.g.: Inherit from Android Service class Override oncreate() & ondestroy (optional) These hook methods are called back by Android to initialize & terminate a Service at the appropriate time public class MyService extends Service {... public void oncreate() {...} } 4 protected void ondestroy() {...} public Ibinder onbind(intent intent) {...} public boolean onunbind(intent intent) {...} public int onstartcommand (Intent intent, int flags, int startid) {...}...

Programming a Bound Service Implementing a Bound Service is similar to a Started Service, e.g.: Inherit from Android Service class Override oncreate() & ondestroy (optional) Override the onbind() lifecycle method Returns an Ibinder that defines a communication channel used for two-way interaction The object returned here is typically initialized at the class scope or in oncreate() developer.android.com/reference/android/app/service.html 5 #onbind(android.content.intent) 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) {...}...

Programming a Bound Service Implementing a Bound Service is similar to a Started Service, e.g.: Inherit from Android Service class Override oncreate() & ondestroy (optional) Override the onbind() lifecycle method Can also implement onunbind() Called when all clients have disconnected from a particular interface published by the Service by calling unbindservice() developer.android.com/reference/android/app/service.html 6 #onunbind(android.content.intent) 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) {...}...

Programming a Bound Service Implementing a Bound Service is similar to a Started Service, e.g.: Inherit from Android Service class Override oncreate() & ondestroy (optional) Override the onbind() lifecycle method Can also implement onunbind() Called when all clients have disconnected from a particular interface published by the service Typically returns false, but can return true to trigger rebind() 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) {...}... developer.android.com/guide/components/bound-services.html#lifecycle 7

Programming a Bound Service Implementing a Bound Service is similar to a Started Service, e.g.: Inherit from Android Service class Override oncreate() & ondestroy (optional) Override the onbind() lifecycle method Can also implement onunbind() onstartcommand() is typically not implemented for a Bound Service Only do this if you want to manage the lifecycle of the Bound Service 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) {...}... developer.android.com/guide/components/bound-services.html#lifecycle 8

Programming a Bound Service Implementing a Bound Service is similar to a Started Service, e.g.: Inherit from Android Service class Override oncreate() & ondestroy (optional) Override the onbind() lifecycle method Can also implement onunbind() onstartcommand() is typically not implemented for a Bound Service Include the Service in the AndroidManifest.xml config file <application... > <activity android:name= ".MyActivity"... </activity> <service android:exported= "true" android:name= ".MyService... </service> </application www.vogella.com/articles/androidservices/article.html 9 has more on Services

Summary Programming two-way communication with Bound Services is straightforward The bulk of the implementations are handled by Android & a client-side callback protocol 10

Summary 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 the onbind() 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 Definition Language (AIDL) 11

: Local Bound Service Communication by Extending the Binder Class d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Professor of Computer Science Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA

Learning Objectives in this Part of the Module Understand how to communicate with Local Bound Services by extending the Binder class Single Process Assign to data member 7 onstart() BindingActivity mservice bindservice() ServiceConnection onserviceconnected() Call getrand() 1 8 Start Bound Service process if it s not already running 2 Intent 4 Dispatch callback Call getservice() 5 LocalService LocalBinder getservice() getrand() 3 onbind() mbinder Return reference to object that implements the IBinder interface 6 Dispatch method & return result See developer.android.com/guide/components/bound-services.html#binder 13

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 Single Process onstart() BindingActivity mservice LocalService LocalBinder getservice() getrand() ServiceConnection onserviceconnected() onbind() mbinder 14

Communication via a Local Binder The 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 Single Process BindingActivity LocalService mservice LocalBinder onstart() bindservice() 1 Start Bound Service process if it s not already running 2 getservice() getrand() ServiceConnection Intent onbind() mbinder 15

Communication via a Local Binder The LocalBinder is a Binder public class LocalBinder extends Binder {... } Single Process BindingActivity mservice LocalService LocalBinder getservice() onstart() ServiceConnection getrand() onbind() 3 Return reference to object that implements the IBinder interface onserviceconnected() 4 Dispatch callback mbinder 16

Communication via a Local Binder The getservice() factory method allows clients to call LocalService methods public class LocalBinder extends Binder { LocalService getservice() { return LocalService.this; } } Single Process BindingActivity LocalService Assign to data member mservice onstart() ServiceConnection LocalBinder getservice() getrand() onbind() Return reference to object that implements the IBinder interface 7 onserviceconnected() mbinder 6 Call getservice() 5 Dispatch method & return result 17

Communication via a Local Binder getrand() is a two-way method call that returns a random number to the caller Single Process onstart() BindingActivity mservice Call getrand() 8 LocalService LocalBinder getservice() getrand() ServiceConnection onserviceconnected() onbind() mbinder 18

Example of Service that Extends the Binder Create a Binder object that returns the current Service instance, which has public methods the client can call Return Service public class LocalService extends Service { instance to client public class LocalBinder extends Binder { LocalService getservice() { return LocalService.this; } } Factory Method for clients private final IBinder mbinder = new LocalBinder (); Called by Android when client invokes bindservice() to return Binder instance public IBinder onbind(intent intent) { return mbinder; } private final Random mgenerator = new Random(); } Called by clients to generate a random number public int getrand() { return mgenerator.nextint(100); } 19

public class BindingActivity extends Activity { LocalService mservice; boolean mbound = false; Example of Client that Uses the Extended Binder The client receive the Binder from the onserviceconnected() callback method & makes calls to the Bound Service using the provided methods Object state protected void onstart() { super.onstart(); Bind to LocalService Intent intent = new Intent(this, LocalService.class); bindservice(intent, mconn, Context.BIND_AUTO_CREATE); } protected void onstop() { Unbind to LocalService super.onstop(); if (mbound) { unbindservice(mconn); mbound = false; } } Calls Service s method public void onbuttonclick(view v) { if (mbound) Toast.makeText(this, mservice.getrand(), Toast.LENGTH_SHORT).show(); } 20

Example of Client that Uses the Extended Binder The client receive the Binder from the onserviceconnected() callback method & makes calls to the Bound Service using the provided methods public class BindingActivity extends Activity {... Defines Service binding callbacks, passed to bindservice() private ServiceConnection mconn = new ServiceConnection() { public void onserviceconnected(componentname classname, IBinder service) { LocalService.LocalBinder binder = (LocalService.LocalBinder)service; mservice = binder.getservice(); mbound = true; } Cast the IBinder & get LocalService instance } public void onservicedisconnected(componentname a) { mbound = false; } }; Called when Service is unexpectedly disconnected 21

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 Single Process Assign to data member 7 onstart() BindingActivity mservice bindservice() ServiceConnection onserviceconnected() Call getrand() 1 8 Start Bound Service process if it s not already running 2 Intent 4 Dispatch callback Call getservice() 22 5 LocalService LocalBinder getservice() getrand() 3 onbind() mbinder Return reference to object that implements the IBinder interface 6 Dispatch method & return result

Summary 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 Single Process Assign to data member 7 onstart() BindingActivity mservice bindservice() ServiceConnection onserviceconnected() Call getrand() 1 8 Start Bound Service process if it s not already running 2 Intent 4 Dispatch callback Call getservice() 23 5 LocalService LocalBinder getservice() getrand() 3 onbind() mbinder Return reference to object that implements the IBinder interface 6 Dispatch method & return result

: Bound Service Communication Via Messengers d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Professor of Computer Science Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA

Learning Objectives in this Part of the Module Understand how to communicate with Bound Services via Messengers Single Process Create Messenger & assign to data member MessengerActivity msvcmsg onstart() bindservice() ServiceConnection 6 1 Call send() to pass a Message to Service Intent Start Bound Service process if it s not already running 2 MessengerService mmessenger onbind() InHandler 3 Return reference to mmessenger 5 onserviceconnected() 4 Dispatch callback handlemessage() 7 Dispatch handlemessage() developer.android.com/guide/components/bound-services.html#messenger 25

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 using AIDL (which is more powerful & complicated) Single Process MessengerActivity msvcmsg MessengerService mmessenger onstart() onbind() ServiceConnection onserviceconnected() InHandler handlemessage() Generalizing to communicate between 26 processes is relatively straightforward

Using a Messenger in a Bound Service Implement a Handler that receives a callback for each call from a client & reference the Handler in a Messenger object Single Process MessengerActivity msvcmsg onstart() bindservice() ServiceConnection onserviceconnected() 1 Intent Start Bound Service process if it s not already running 2 MessengerService mmessenger onbind() InHandler handlemessage() 27

Using a Messenger in a Bound Service Messenger creates IBinder that Service returns to clients from onbind() public IBinder onbind(intent intent) { return mmessenger.getbinder(); } Single Process MessengerActivity MessengerService Create Messenger & assign to data member msvcmsg onstart() ServiceConnection mmessenger onbind() InHandler 3 Return reference to mmessenger 5 onserviceconnected() 4 handlemessage() Dispatch callback developer.android.com/reference/android/os/messenger.html#getbinder() 28

Using a Messenger in a Bound Service This method can perform an action, e.g., display the Message contents, do some processing, send a reply, etc. Single Process MessengerActivity msvcmsg 6 Call send() to pass a Message to Service MessengerService mmessenger onstart() onbind() ServiceConnection InHandler onserviceconnected() handlemessage() 7 Dispatch handlemessage() 29

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); } Example Using a Messenger in a Bound Service Handler for incoming client Messages Instruct Service to do some action Target for clients to send Messages to InHandler final Messenger mmessenger = new Messenger(new InHandler()); } public IBinder onbind(intent intent) { return mmessenger.getbinder(); } Return Ibinder so clients can send Messages to Service developer.android.com/reference/android/os/messenger.html 30 #Messenger(android.os.Handler)

Example Using a Messenger in an Activity public class MessengerActivity extends Activity {... Messenger msvcmsg = null; Means to communicate w/service boolean mbound; Flag indicating if Service is bound private ServiceConnection mconnection = new ServiceConnection() { public void onserviceconnected(componentname classname, IBinder service) { msvcmsg = new Messenger(service); mbound = true; } Called when connection with Service has been established, giving the object to interact with the Service public void onservicedisconnected(componentname classname) { msvcmsg = null; mbound = false; } Called when Service is unexpectedly disconnected }; developer.android.com/reference/android/os/messenger.html 31 #Messenger(android.os.IBinder)

32 public class MessengerActivity extends Activity {... protected void onstart() { Bind to the service super.onstart(); bindservice(new Intent(this, MessengerService.class), mconnection, Context.BIND_AUTO_CREATE); } protected void onstop() { Unbind from the service 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); }... Example Using a Messenger in an Activity... msvcmsg.send(msg); Create & send a Message to Messenger in Service, using a 'what' value

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 Single Process MessengerActivity msvcmsg onstart() ReplyHandler 6 Call send() to pass Message to Service, including another Messenger for the reply path MessengerService mmessenger onbind() InHandler handlemessage() 8 handlemessage() Dispatch reply 7 Dispatch handlemessage() We didn t show the code for two-way 33 communication in our example

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 Create Messenger & assign to data member MessengerActivity msvcmsg onstart() bindservice() ServiceConnection 6 1 Call send() to pass Message to Service Intent Start Bound Service process if it s not already running 2 MessengerService mmessenger onbind() InHandler 3 Return reference to mmessenger 5 onserviceconnected() 4 Dispatch callback handlemessage() 7 Dispatch handlemessage() Some additional programming is 34 required to use Messengers for IPC

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 to handle one call at a time without requiring thread-safe programming Single Process Create Messenger & assign to data member MessengerActivity msvcmsg onstart() bindservice() ServiceConnection 6 1 Call send() to pass Message to Service Intent Start Bound Service process if it s not already running 2 MessengerService mmessenger onbind() InHandler 3 Return reference to mmessenger 5 onserviceconnected() 4 Dispatch callback handlemessage() 7 Dispatch handlemessage() If your Service must be multi-threaded 35 then you ll need AIDL (covered next)

: Advanced Bound Service Communication Overview of the AIDL & Binder RPC d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Professor of Computer Science Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA

Learning Objectives in this Part of the Module Understand AIDL & Binder RPC mechanisms for communicating with Bound Services Assign Proxy to data member 5 Process A DownloadActivity initiatedownload() onstart() mboundservice bindservice() ServiceConnection onserviceconnected() 1 Binder IPC Mechanism downloadimage() 6 Intent Start Bound Service process if it s not 2 already running 4 Dispatch callback Process B DownloadService onbind() mbinder ImageBinder downloadimage() 3 Return ref to Binder object 7 Stub dispatches method & returns result AIDL & Binder RPC are the most powerful 37 Android local IPC mechanism

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 sidestepped this issue by collocating the Activity & the Service in the same process address space Client Process DownloadActivity mboundservice Server Process DownloadService ImageBinder downloadimage() 38

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 the objects across the process boundary Marshaling converts data from native format into a linearized format Client Process DownloadActivity mboundservice 1 Server Process DownloadService ImageBinder downloadimage() en.wikipedia.org/wiki/marshalling_(computer_science) 39 has more info

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 the objects across the process boundary Marshaling converts data from native format into a linearized format Demarshaling converts data from the linearized format into native format Client Process DownloadActivity mboundservice 2 Server Process DownloadService ImageBinder downloadimage() en.wikipedia.org/wiki/marshalling_(computer_science) 40 has more info

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 the objects 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 Client Process DownloadActivity mboundservice interface IDownload { String downloadimage (String uri); } Server Process DownloadService ImageBinder downloadimage() 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 the objects 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 Client Process DownloadActivity mboundservice interface IDownload { String downloadimage (String uri); } Server Process DownloadService ImageBinder downloadimage() MyService.Stub.Proxy AIDL Compiler MyService.Stub developer.android.com/guide/components/aidl.html 42 has AIDL overview

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 the objects 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 Client Process DownloadActivity Binder IPC Mechanism Server Process DownloadService mboundservice MyService.Stub.Proxy 1 Call method downloadimage() 2 Return results to caller ImageBinder downloadimage() MyService.Stub elinux.org/android_binder has more 43 info on Android Binder RPC

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 Client Process DownloadActivity Binder IPC Mechanism Server Process DownloadService mboundservice MyService.Stub.Proxy 1 Call method downloadimage() 2 Return results to caller ImageBinder downloadimage() MyService.Stub 44

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 Client Process DownloadActivity Binder IPC Mechanism Server Process NDKDownloadService mboundservice 1 Call method downloadimage() 2 Return results to caller C/C++ code downloadimage() MyService.Stub.Proxy NDKService::Stub sites.google.com/site/io/anatomy--physiology-of-an-android 45 has more info

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 Caller s data is marshaled into parcels, copied to callee s process, & demarshaled into what callee expects Client Process DownloadActivity Binder IPC Mechanism Server Process DownloadService mboundservice MyService.Stub.Proxy 1 Call method downloadimage() 2 Return results to caller ImageBinder downloadimage() MyService.Stub 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 Caller s data is marshaled into parcels, copied to callee s process, & demarshaled into what callee expects Two-way method invocations are synchronous (block the caller) One-way method invocations do not block the caller Client Process DownloadActivity Binder IPC Mechanism Server Process DownloadService mboundservice MyService.Stub.Proxy 1 Call method downloadimage() 2 Return results to caller ImageBinder downloadimage() MyService.Stub Caller thread blocks waiting 47 for results from the Service

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 Caller s data is marshaled into parcels, copied to callee s 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 Client Process DownloadActivity mboundservice ReplyHandler 1 Binder IPC Mechanism Call oneway method setcallback() Server Process DownloadService ImageBinder setcallback() Client passes callback object 48 via oneway method to Service

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 Caller s data is marshaled into parcels, copied to callee s 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 Client Process DownloadActivity mboundservice ReplyHandler Binder IPC Mechanism 1 Call oneway method setcallback() Server Process DownloadService ImageBinder setcallback() Caller thread doesn t 49 block waiting for results

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 Caller s data is marshaled into parcels, copied to callee s 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 Client Process DownloadActivity Binder IPC Mechanism Server Process DownloadService mboundservice ReplyHandler 2 Call oneway method sendpath() ImageBinder downloadcallback() sendpath() Service invokes a one-way 50 method to return results

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 Caller s data is marshaled into parcels, copied to callee s 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 Client Process DownloadActivity Binder IPC Mechanism Server Process DownloadService mboundservice MyService.Stub.Proxy 1 Call method downloadimage() 2 Return results to caller ImageBinder downloadimage() MyService.Stub 51

Summary Android provides a wide range of local IPC mechanisms for communicating with Bound Services www.vogella.com/tutorials.html There are many Android tutorials 52 & resources available online

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 It s used with the Binder RPC mechanism to implement the Broker pattern Process Boundary Broker connects clients with remote objects by mediating invocations from clients to remote objects, while encapsulating the details of IPC or network communication See www.kircher-schwanninger.de/michael/publications/brokerrevisited.pdf 53

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 It s used with the Binder RPC mechanism to implement the Broker pattern Process Boundary Many other patterns are used to implement AIDL & Binder RPC e.g., Proxy, Adapter, Activator, etc. 54