Pages

Sunday 22 September 2019

Android Interface Definition Language (AIDL)

  • AIDL used to perform IPC (inter process communication). In simple words, when we want to communicate with service of other application then we may use AIDL
  • Que: How AIDL different then ContentProvider?
    Ans: Using ContentProvider we can access data of other application and we may query on data. While Using AIDL we can do interaction with background Service of other application.
We are going to show one example of AIDL Server and Client application when client app will get string and one student object from server app for demo purpose you can do any process and send result from server app to client app in realtime. Lets start with server application first.
  1. SERVER APP:
    Consider that our app's applicationId (package name) is "com.example.aidl.server".
    AIDL is nothing but the interface through client app will get callback from server app.
    So Basically in server app we have a Service and  a AIDL file (interface).
    We need to create interface into main>aidl path of the main (app) module.
    Into aidl folder create same package name as our applicationId, and add following aidl file.


    Now create following one service at your desired package.


    Now you have to rebuild app before move further as android will create abstract class of binder object from aidl file. As you see above in service we have implemented object from MyAidl.Stub. and onBind method of service will return this AIDL.Stub instance (which is actually binder). so Client app will bind this service and get instance of Aidl stub. using this client app can call getStudentObject and getString methods. We can pass custom class using parcelable implementation. We need to create one aidl file too for parcelable class. Following is an example of that.


    That's it for server app.
  2. CLIENT APP:
    Consider out client app's applicationId (package name) is "com.example.aidl.client".
    First of all we need same aidl files as server have so we simply copy paste those files.
    Here is one thing need to consider "MyAidl.aidl" file should be in package name same as server. We need "Student.aidl" and "Student.kt" both files same as server. you can place "Student.kt" file at your desired package name and in aidl folder we have to put "Student.aidl" file in same package name as we put "Student.kt" file in our client app. Now we have to rebuild app to move further so android studio will generate Stub classes. We can bind server's service and we can get string and student object from it following way.


    Using above activity we have bind service and get data from other app.
    That's it for client app.
    You can find both app at this github url: https://github.com/k9428/Aidl_demo

    So this way we can do interprocess communication using AIDL.

No comments :

Post a Comment