SlideShare a Scribd company logo
1 of 15
Malwinder Pal Singh
Assistant Software Developer
Inter Process Communication
in Android
Introduction to IPC using Messenger
• Android offers a mechanism for inter-process communication (IPC) using remote
procedure calls (RPCs), in which a method is called by an activity or other
application component, but executed remotely (in another process), with any
result returned back to the caller.
• This entails decomposing a method call and its data to a level the operating system
can understand, transmitting it from the local process and address space to the
remote process and address space, then reassembling and re-enacting the call
there.
• Return values are then transmitted in the opposite direction.
• Android provides all the code to perform these IPC transactions, so you can focus
on defining and implementing the RPC programming interface.
Android Interface Definition Language versus
Messenger
• Using AIDL is necessary only if you allow clients from different applications to
access your service for IPC and want to handle multithreading in your service.
• If you do not need to perform concurrent IPC across different applications, you
should create your interface by implementing a Binder or, if you want to perform
IPC, but do not need to handle multithreading, implement your interface using a
Messenger.
• Executing all the tasks (passing messages) is sequential by design as the
messages are processed on a single thread by the Handler to which it belongs
whereas AIDL can execute tasks concurrently on binder threads.
Implementation in Service
• The Service should implement (contain) a Handler instance that receives a call-back
(using handleMessage() for instance) for each call from the client.
public class LocationService extends Service {
public static final int REQUEST_LOCATION= 1;
class ServiceHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case REQUEST_LOCATION :
replyLocation(40.22,32.21);
break;
default:
super.handleMessage(msg);
Implementation in Service
The Handler is used to create a Messenger object which in itself is actually a reference
to the Handler.
The Messenger creates an IBinder (via getBinder()) that the Service returns to
clients from onBind().
//Inside LocationService
Messenger mServiceMessenger = new Messenger(new ServiceHandler());
@Override
public IBinder onBind(Intent intent) {
return mServiceMessenger.getBinder();
}
Implementation in Client
Clients use the IBinder object in its ServiceConnection implementation to instantiate
the Messenger object.
Messenger mMessenger;
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mMessenger = new Messenger(service);
}
}
Implementation in Client
This messenger refers to Service’s Handler which the client uses to send Message (with
send() for instance) objects to the Service’s Handler. So the Service receives the
messages in its Handler.handleMessage().
private void requestLocation() {
Message msg = Message.obtain(null, LocationService.REQUEST_LOCATION);
try {
mMessenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
Changes in Manifest
Make sure to have this entry in your manifest in order for the Service to work properly in a
different process.
<service
android:name="com.example.app.LocationService"
android:process=":my_process">
</service>
If the name assigned to this attribute begins with a colon (':'), a new process, private to the
application, is created when it's needed and the service runs in that process.
If the process name begins with a lowercase character, the service will run in a global
process of that name, provided that it has permission to do so. This allows components in
different applications to share a process, reducing resource usage.
Modifications in Incoming Handler
Weak References
A weak reference, simply put, is a reference that isn't strong enough to force an object
to remain in memory. Weak references allow you to leverage the garbage collector's
ability to determine reachability for you, so you don't have to do it yourself. You create
a weak reference like this:
WeakReference weakWidget = new WeakReference(widget);
and then elsewhere in the code you can use weakWidget.get() to get the
actual Widget object. Of course the weak reference isn't strong enough to prevent
garbage collection, so you may find (if there are no strong references to the widget)
that weakWidget.get() suddenly starts returning null.
Modifications in Incoming Handler
If IncomingHandler class is not static, it will have a reference to
your Service object.
static class ServiceHandler extends Handler {
private final WeakReference<LocationService> mService;
ServiceHandler(LocationService service) {
mService = new WeakReference<LocationService>(service);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case REQUEST_LOCATION :
mService.replyLocation(40.22,32.21);
break;
default:
super.handleMessage(msg);
Android Interface Definition Language
Concept
AIDL allows you to define the programming interface that both the client and
service agree upon in order to communicate with each other using inter-process
communication.
If you do not need to perform concurrent IPC across different applications, you
should create your interface by implementing a Binder or, if you want to perform
IPC, but do not need to handle multithreading, implement your interface using a
Messenger.
Using AIDL is necessary only if you allow clients from different applications to access your
service for IPC and want to handle multithreading in your service.
Android Interface Definition Language
Defining an AIDL interface
To create a bounded service using AIDL, follow these steps:
Create the .aidl file
This file defines the programming interface with method signatures.
Implement the interface
The Android SDK tools generate an interface in the Java programming language, based
on your .aidl file. This interface has an inner abstract class named Stub that
extends Binder and implements methods from your AIDL interface. You must extend
the Stub class and implement the methods.
Expose the interface to clients
Implement a Service and override onBind() to return your implementation of
the Stub class.
Create the .aidl file
// IRemoteService.aidl
package com.example.android;
// Declare any non-default types here with import statements
/** Example service interface */
interface IRemoteService {
int getPid();
void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString);
}
Here is an example .aidl file:
Simply save your .aidl file in your project's src/ directory and when you build your application, the SDK tools
generate the IBinder interface file in your project's gen/ directory.
Implement the interface
public class RemoteService extends Service {
private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
public int getPid(){
return Process.myPid();
}
public void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, String aString) {
// Does nothing
}
};
Expose the interface to clients
IRemoteService mIRemoteService;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder
service) {
mIRemoteService = IRemoteService.Stub.asInterface(service);
}
public void onServiceDisconnected(ComponentName className) {
mIRemoteService = null;
}
};

More Related Content

What's hot

Basic android-ppt
Basic android-pptBasic android-ppt
Basic android-pptSrijib Roy
 
Introduction to fragments in android
Introduction to fragments in androidIntroduction to fragments in android
Introduction to fragments in androidPrawesh Shrestha
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 
Data Persistence in Android with Room Library
Data Persistence in Android with Room LibraryData Persistence in Android with Room Library
Data Persistence in Android with Room LibraryReinvently
 
Android activity
Android activityAndroid activity
Android activityKrazy Koder
 
Android application structure
Android application structureAndroid application structure
Android application structureAlexey Ustenko
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
Flutter presentation.pptx
Flutter presentation.pptxFlutter presentation.pptx
Flutter presentation.pptxFalgunSorathiya
 
Android app development ppt
Android app development pptAndroid app development ppt
Android app development pptsaitej15
 
Overview of Android binder IPC implementation
Overview of Android binder IPC implementationOverview of Android binder IPC implementation
Overview of Android binder IPC implementationChethan Pchethan
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate pptAneega
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017Hardik Trivedi
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node jsAkshay Mathur
 

What's hot (20)

Basic android-ppt
Basic android-pptBasic android-ppt
Basic android-ppt
 
Introduction to fragments in android
Introduction to fragments in androidIntroduction to fragments in android
Introduction to fragments in android
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Data Persistence in Android with Room Library
Data Persistence in Android with Room LibraryData Persistence in Android with Room Library
Data Persistence in Android with Room Library
 
Android Services
Android ServicesAndroid Services
Android Services
 
Recyclerview in action
Recyclerview in action Recyclerview in action
Recyclerview in action
 
Android activity
Android activityAndroid activity
Android activity
 
Android application structure
Android application structureAndroid application structure
Android application structure
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Android Basic Components
Android Basic ComponentsAndroid Basic Components
Android Basic Components
 
Aidl service
Aidl serviceAidl service
Aidl service
 
Flutter presentation.pptx
Flutter presentation.pptxFlutter presentation.pptx
Flutter presentation.pptx
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Android app development ppt
Android app development pptAndroid app development ppt
Android app development ppt
 
Overview of Android binder IPC implementation
Overview of Android binder IPC implementationOverview of Android binder IPC implementation
Overview of Android binder IPC implementation
 
Flutter
FlutterFlutter
Flutter
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Android Location and Maps
Android Location and MapsAndroid Location and Maps
Android Location and Maps
 

Similar to IPC in Android using Messenger and AIDL

AIDL - Android Interface Definition Language
AIDL  - Android Interface Definition LanguageAIDL  - Android Interface Definition Language
AIDL - Android Interface Definition LanguageArvind Devaraj
 
Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1Utkarsh Mankad
 
Architecture your android_application
Architecture your android_applicationArchitecture your android_application
Architecture your android_applicationMark Brady
 
Introduction to Google Guice
Introduction to Google GuiceIntroduction to Google Guice
Introduction to Google GuiceKnoldus Inc.
 
Android intents, notification and broadcast recievers
Android intents, notification and broadcast recieversAndroid intents, notification and broadcast recievers
Android intents, notification and broadcast recieversUtkarsh Mankad
 
Android Training (Services)
Android Training (Services)Android Training (Services)
Android Training (Services)Khaled Anaqwa
 
Background Tasks with Worker Service
Background Tasks with Worker ServiceBackground Tasks with Worker Service
Background Tasks with Worker Servicessusere19c741
 
Android App Development - 08 Services
Android App Development - 08 ServicesAndroid App Development - 08 Services
Android App Development - 08 ServicesDiego Grancini
 
Wcf architecture overview
Wcf architecture overviewWcf architecture overview
Wcf architecture overviewArbind Tiwari
 
Enterprise Java Microservices : creating and managing large-scale Java applic...
Enterprise Java Microservices : creating and managing large-scale Java applic...Enterprise Java Microservices : creating and managing large-scale Java applic...
Enterprise Java Microservices : creating and managing large-scale Java applic...Manning Publications
 
Vert.x for Microservices Architecture
Vert.x for Microservices ArchitectureVert.x for Microservices Architecture
Vert.x for Microservices ArchitectureIdan Fridman
 
Real-Time Communication
Real-Time CommunicationReal-Time Communication
Real-Time Communicationssusere19c741
 
Service Oriented Architecture in NodeJS
Service Oriented Architecture in NodeJSService Oriented Architecture in NodeJS
Service Oriented Architecture in NodeJSAndolasoft Inc
 
Android应用开发简介
Android应用开发简介Android应用开发简介
Android应用开发简介easychen
 
Dependency Injection або Don’t call me, I’ll call you
Dependency Injection або Don’t call me, I’ll call youDependency Injection або Don’t call me, I’ll call you
Dependency Injection або Don’t call me, I’ll call youDmytro Mindra
 

Similar to IPC in Android using Messenger and AIDL (20)

AIDL - Android Interface Definition Language
AIDL  - Android Interface Definition LanguageAIDL  - Android Interface Definition Language
AIDL - Android Interface Definition Language
 
Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1
 
Architecture your android_application
Architecture your android_applicationArchitecture your android_application
Architecture your android_application
 
Introduction to Google Guice
Introduction to Google GuiceIntroduction to Google Guice
Introduction to Google Guice
 
Android intents, notification and broadcast recievers
Android intents, notification and broadcast recieversAndroid intents, notification and broadcast recievers
Android intents, notification and broadcast recievers
 
Android Training (Services)
Android Training (Services)Android Training (Services)
Android Training (Services)
 
Android101
Android101Android101
Android101
 
Background Tasks with Worker Service
Background Tasks with Worker ServiceBackground Tasks with Worker Service
Background Tasks with Worker Service
 
Android App Development - 08 Services
Android App Development - 08 ServicesAndroid App Development - 08 Services
Android App Development - 08 Services
 
Wcf architecture overview
Wcf architecture overviewWcf architecture overview
Wcf architecture overview
 
Enterprise Java Microservices : creating and managing large-scale Java applic...
Enterprise Java Microservices : creating and managing large-scale Java applic...Enterprise Java Microservices : creating and managing large-scale Java applic...
Enterprise Java Microservices : creating and managing large-scale Java applic...
 
Vert.x for Microservices Architecture
Vert.x for Microservices ArchitectureVert.x for Microservices Architecture
Vert.x for Microservices Architecture
 
Real-Time Communication
Real-Time CommunicationReal-Time Communication
Real-Time Communication
 
Basic java
Basic java Basic java
Basic java
 
Binder: Android IPC
Binder: Android IPCBinder: Android IPC
Binder: Android IPC
 
Service Oriented Architecture in NodeJS
Service Oriented Architecture in NodeJSService Oriented Architecture in NodeJS
Service Oriented Architecture in NodeJS
 
Embedded Android : System Development - Part IV (Android System Services)
Embedded Android : System Development - Part IV (Android System Services)Embedded Android : System Development - Part IV (Android System Services)
Embedded Android : System Development - Part IV (Android System Services)
 
2007 Zend Con Mvc
2007 Zend Con Mvc2007 Zend Con Mvc
2007 Zend Con Mvc
 
Android应用开发简介
Android应用开发简介Android应用开发简介
Android应用开发简介
 
Dependency Injection або Don’t call me, I’ll call you
Dependency Injection або Don’t call me, I’ll call youDependency Injection або Don’t call me, I’ll call you
Dependency Injection або Don’t call me, I’ll call you
 

Recently uploaded

Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 

Recently uploaded (20)

Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 

IPC in Android using Messenger and AIDL

  • 1. Malwinder Pal Singh Assistant Software Developer Inter Process Communication in Android
  • 2. Introduction to IPC using Messenger • Android offers a mechanism for inter-process communication (IPC) using remote procedure calls (RPCs), in which a method is called by an activity or other application component, but executed remotely (in another process), with any result returned back to the caller. • This entails decomposing a method call and its data to a level the operating system can understand, transmitting it from the local process and address space to the remote process and address space, then reassembling and re-enacting the call there. • Return values are then transmitted in the opposite direction. • Android provides all the code to perform these IPC transactions, so you can focus on defining and implementing the RPC programming interface.
  • 3. Android Interface Definition Language versus Messenger • Using AIDL is necessary only if you allow clients from different applications to access your service for IPC and want to handle multithreading in your service. • If you do not need to perform concurrent IPC across different applications, you should create your interface by implementing a Binder or, if you want to perform IPC, but do not need to handle multithreading, implement your interface using a Messenger. • Executing all the tasks (passing messages) is sequential by design as the messages are processed on a single thread by the Handler to which it belongs whereas AIDL can execute tasks concurrently on binder threads.
  • 4. Implementation in Service • The Service should implement (contain) a Handler instance that receives a call-back (using handleMessage() for instance) for each call from the client. public class LocationService extends Service { public static final int REQUEST_LOCATION= 1; class ServiceHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case REQUEST_LOCATION : replyLocation(40.22,32.21); break; default: super.handleMessage(msg);
  • 5. Implementation in Service The Handler is used to create a Messenger object which in itself is actually a reference to the Handler. The Messenger creates an IBinder (via getBinder()) that the Service returns to clients from onBind(). //Inside LocationService Messenger mServiceMessenger = new Messenger(new ServiceHandler()); @Override public IBinder onBind(Intent intent) { return mServiceMessenger.getBinder(); }
  • 6. Implementation in Client Clients use the IBinder object in its ServiceConnection implementation to instantiate the Messenger object. Messenger mMessenger; private ServiceConnection mServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mMessenger = new Messenger(service); } }
  • 7. Implementation in Client This messenger refers to Service’s Handler which the client uses to send Message (with send() for instance) objects to the Service’s Handler. So the Service receives the messages in its Handler.handleMessage(). private void requestLocation() { Message msg = Message.obtain(null, LocationService.REQUEST_LOCATION); try { mMessenger.send(msg); } catch (RemoteException e) { e.printStackTrace(); } }
  • 8. Changes in Manifest Make sure to have this entry in your manifest in order for the Service to work properly in a different process. <service android:name="com.example.app.LocationService" android:process=":my_process"> </service> If the name assigned to this attribute begins with a colon (':'), a new process, private to the application, is created when it's needed and the service runs in that process. If the process name begins with a lowercase character, the service will run in a global process of that name, provided that it has permission to do so. This allows components in different applications to share a process, reducing resource usage.
  • 9. Modifications in Incoming Handler Weak References A weak reference, simply put, is a reference that isn't strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector's ability to determine reachability for you, so you don't have to do it yourself. You create a weak reference like this: WeakReference weakWidget = new WeakReference(widget); and then elsewhere in the code you can use weakWidget.get() to get the actual Widget object. Of course the weak reference isn't strong enough to prevent garbage collection, so you may find (if there are no strong references to the widget) that weakWidget.get() suddenly starts returning null.
  • 10. Modifications in Incoming Handler If IncomingHandler class is not static, it will have a reference to your Service object. static class ServiceHandler extends Handler { private final WeakReference<LocationService> mService; ServiceHandler(LocationService service) { mService = new WeakReference<LocationService>(service); } @Override public void handleMessage(Message msg) { switch (msg.what) { case REQUEST_LOCATION : mService.replyLocation(40.22,32.21); break; default: super.handleMessage(msg);
  • 11. Android Interface Definition Language Concept AIDL allows you to define the programming interface that both the client and service agree upon in order to communicate with each other using inter-process communication. If you do not need to perform concurrent IPC across different applications, you should create your interface by implementing a Binder or, if you want to perform IPC, but do not need to handle multithreading, implement your interface using a Messenger. Using AIDL is necessary only if you allow clients from different applications to access your service for IPC and want to handle multithreading in your service.
  • 12. Android Interface Definition Language Defining an AIDL interface To create a bounded service using AIDL, follow these steps: Create the .aidl file This file defines the programming interface with method signatures. Implement the interface The Android SDK tools generate an interface in the Java programming language, based on your .aidl file. This interface has an inner abstract class named Stub that extends Binder and implements methods from your AIDL interface. You must extend the Stub class and implement the methods. Expose the interface to clients Implement a Service and override onBind() to return your implementation of the Stub class.
  • 13. Create the .aidl file // IRemoteService.aidl package com.example.android; // Declare any non-default types here with import statements /** Example service interface */ interface IRemoteService { int getPid(); void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString); } Here is an example .aidl file: Simply save your .aidl file in your project's src/ directory and when you build your application, the SDK tools generate the IBinder interface file in your project's gen/ directory.
  • 14. Implement the interface public class RemoteService extends Service { private final IRemoteService.Stub mBinder = new IRemoteService.Stub() { public int getPid(){ return Process.myPid(); } public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) { // Does nothing } };
  • 15. Expose the interface to clients IRemoteService mIRemoteService; private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { mIRemoteService = IRemoteService.Stub.asInterface(service); } public void onServiceDisconnected(ComponentName className) { mIRemoteService = null; } };