Android AIDL Example with Code Description – IPC

Android AIDL Example with Code Description – IPC

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

Before we learn about Android Interface Definition Language (AIDL), Let us know why it is required? The answer is very simple. Each Android app run in it’s own process. So one application can’t directly access another app’s memory space. If you want to access some data from one application to another application, then we need to use  inter process communication (IPC) like other platforms. So in Android IPC is otherwise known as AIDL. For this purpose Android provides a technique called Android Interface Definition Language (AIDL). It is a lightweight implementation of IPC just like C/C++ languages.

So to communicate between process or you say between applications, we need to implement AIDL in our Android application. In other words you can say the AIDL technique is a light weighted client server architecture in form of a service, which helps multiple applications to communicate between them self.  To do so we need the below steps.

1. AIDL interface– Define a AIDL interface which will be the interface between your applications.
2. Implement the the remote service– Remote service holds your data/method to expose to other applications for accessing data.
3. Expose the remote service to other local clients- The data/method we need to share with other applications needs to be expose so that other application can access and share data from the remote service.

To make the example simple, lets take an simple example. We will develop a remote service for addition of two numbers. That means we will get user input from client application, then send the data to remote service and get the result back from remote service. I thing it is good enough to learn basic of remote server using AIDL.

Creating our AIDL interface- Define a AIDL interface which will be the interface between your applications

here we just define the method signature (prototype), which we need to expose to other clients(apps). please note that  all Java primitive datatypes are supported in AIDL. You can also use your own user define datatypes in AIDL. Also you can use Parcelable classes here. but here we will discuss with basic primitive datatypes to make the example simpler. So below is the code snippet.

Put the below file in your source folder like this: \src\com\techblogon\aidlexample\IAddService.aidl

Interface File: IAddService.aidl

package com.techblogon.aidlexample;
// Declare the communication interface which holds all of our exposed functions.
interface IAddService {
    // WE can pass values along with in, out, or inout parameters.
    // Android Java Primitive datatypes (such as int,, string, boolean, etc.) can only be passed in.
    int add(in int ValueFirst, in int valueSecond);
}

Note: In the above code  the method add() will be exposed to local clients.

Implementing our Remote Service – 

After we created our AIDL file and put it in proper place as above, the inbuilt AIDL tool in Eclipse will generate a new file with ‘.java’ extension with the same name of your AIDL file, which your can find in your project’s ‘jen’ folder. So now we have a new file called  ‘IAddService.java’  in the location \gen\com\techblogon\aidlexample. This is an auto-generated file so don’t edit it at all. The mail purpose of this calls is that it contains a Stub class that we need to implement for our remote service.

To implementing our remote service, We need to create a new service class by extending the Android Service class (AddService in our case). Then we will return IBinder from onBind() method in our service class, which represents the implementation of our remote service. To implement IBinder, we need to subclass IAddService.Stub class from the auto-generated Java code. Then we need to implement the code logic for our exposed method called add() in our case, which we just declared in the AIDL interface file. Then his method add() will be called from client side code. Have a look into the below code snippet.

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

Put the below file in your source folder like this: \src\com\techblogon\aidlexample\AddService.Java

Remote Service File: AddService.Java

package com.techblogon.aidlexample;
import com.techblogon.aidlexample.IAddService;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
/**
* This AddService class exposes the remote service (functions in AIDL file, which we need to expose to other apps) to the client
*/
public class AddService extends Service {
  private static final String TAG = “AddService”;
  @Override
  public void onCreate() {
    super.onCreate();
    Log.i(TAG, “onCreate()”);
  }
  @Override
  public IBinder onBind(Intent intent) {
    return new IAddService.Stub() {
      /**
       * In the AIDL file we just add the declaration of the function
       * here is the real implementation of the add() function below
       */
      public int add(int ValueFirst, int valueSecond) throws RemoteException {
        Log.i(TAG, String.format(“AddService.add({5dca631369e527f98bccd3169e55d368b252b7d92eaa74378a6c1f3352a06d08}d, {5dca631369e527f98bccd3169e55d368b252b7d92eaa74378a6c1f3352a06d08}d)”,ValueFirst, valueSecond));
        return (ValueFirst + valueSecond);
      }
    };
  }
  @Override
  public void onDestroy() {
    super.onDestroy();
    Log.d(TAG, “onDestroy()”);
  }
}

 Exposing our Remote Service to Local Clients

After we implemented the onBind() properly in our service class as above, now we are ready to connect to our service from local client. For this we will have a simple Activity class from where we will connect to our remote service and call the exposed  add() function from the service . To establish the connection between service and local client, we need to create a new inner class by implementing Android ServiceConnection class in side our activity class (AIDLActivity in our case). So our  AIDLActivity class  implemented AddServiceConnection inner class by implementing onServiceConnected() and onServiceDiconnected()  methods. These methods are the callbacks, which will get the stub implementation of the remote service on connection. Then we just need to type cast them from our Stubs to our AIDL service implementation. So to do so, we need to use the IAddService.Stub.asInterface((IBinder) boundService) helper method. From here we will have a local service pointer to accessing the data and methods. So initService() is our method which is called from Activity’s onCreate()method to established the connection. Then when we click on ‘Result’ button theonClickButtonResult() method will be call and we have called our remote service’s add()method there.

Put the below file in your source folder like this: \src\com\techblogon\aidlexample\AIDLActivity.Java

Local Client  Activity File: AIDLActivity.Java

package com.techblogon.aidlexample;
import com.techblogon.aidlexample.IAddService;
import com.techblogon.aidlexample.R;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class AIDLActivity extends Activity {
  private static final String TAG = “AIDLExample”;
  IAddService service;
  AddServiceConnection connection;
  /**
   * This is the class which represents the actual service-connection.
   * It type casts the bound-stub implementation of the service class to our AIDL interface.
   */
  class AddServiceConnection implements ServiceConnection {
    public void onServiceConnected(ComponentName name, IBinder boundService) {
      service = IAddService.Stub.asInterface((IBinder) boundService);
      Log.i(TAG, “onServiceConnected(): Connected”);
      Toast.makeText(AIDLActivity.this, “AIDLExample Service connected”, Toast.LENGTH_LONG).show();
    }
    public void onServiceDisconnected(ComponentName name) {
      service = null;
      Log.i(TAG, “onServiceDisconnected(): Disconnected”);
      Toast.makeText(AIDLActivity.this, “AIDLExample Service Connected”, Toast.LENGTH_LONG).show();
    }
  }
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aidl);
initService();
}
public void onClickButtonResult(View v)
{
      TextView value1 = (TextView) findViewById(R.id.editTextValue1);
      EditText value2  = (EditText) findViewById(R.id.editTextValue2);
      EditText result = (EditText) findViewById(R.id.editTextResult);
      int n1 =0, n2 =0, res = 1;
      n1 = Integer.parseInt(value1.getText().toString());
      n2 = Integer.parseInt(value2.getText().toString());
   try {
     res = service.add(n1, n2);
   } catch (RemoteException e) {
     Log.i(TAG, “Data fetch failed with: “ + e);
     e.printStackTrace();
   }
   result.setText(new Integer(res).toString());
}
  /** This is our function which binds our activity(MainActivity) to our service(AddService). */
  private void initService() {
Log.i(TAG, “initService()” );
connection = new AddServiceConnection();
    Intent i = new Intent();
    i.setClassName(“com.techblogon.aidlexample”, com.techblogon.aidlexample.AddService.class.getName());
    boolean ret = bindService(i, connection, Context.BIND_AUTO_CREATE);
    Log.i(TAG, “initService() bound value: “ + ret);
  }
  /** This is our function to un-binds this activity from our service. */
  private void releaseService() {
    unbindService(connection);
    connection = null;
    Log.d(TAG, “releaseService(): unbound.”);
  }
@Override
protected void onDestroy() {
super.onDestroy();
releaseService();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

XML Layout (activity_aidl.xml)

Our UI contains simple elements. We have used 2 EditText for getting user input and one button for getting result. The result field is also an EditText with editable false. You can use any other controls. Also we have used a Textview for showing some informations ad hints.

<RelativeLayout xmlns:android=“http://schemas.android.com/apk/res/android”
    xmlns:tools=“http://schemas.android.com/tools”
    android:layout_width=“match_parent”
    android:layout_height=“match_parent”
    android:paddingBottom=“@dimen/activity_vertical_margin”
    android:paddingLeft=“@dimen/activity_horizontal_margin”
    android:paddingRight=“@dimen/activity_horizontal_margin”
    android:paddingTop=“@dimen/activity_vertical_margin”
    tools:context=“.MainActivity” >
      <TextView
        android:id=“@+id/textViewTitle”
        android:layout_width=“wrap_content”
        android:layout_height=“wrap_content”
        android:layout_alignParentTop=“true”
        android:layout_centerHorizontal=“true”
        android:text=“Enter 2 digits for addition, then click result button for getting the result form the service using AIDL.” />
    <EditText
        android:id=“@+id/editTextValue1”
        android:layout_width=“wrap_content”
        android:layout_height=“wrap_content”
        android:layout_below=“@+id/textViewTitle”
        android:layout_centerHorizontal=“true”
        android:layout_marginTop=“35dp”
        android:hint=“Enter a number”
        android:ems=“10”
        android:inputType=“number” />
    <EditText
        android:id=“@+id/editTextValue2”
        android:layout_width=“wrap_content”
        android:layout_height=“wrap_content”
        android:layout_below=“@+id/editTextValue1”
        android:layout_centerHorizontal=“true”
        android:layout_marginTop=“33dp”
        android:hint=“Enter a number”
        android:ems=“10”
        android:inputType=“number”/>
    <EditText
        android:id=“@+id/editTextResult”
        android:layout_width=“wrap_content”
        android:layout_height=“wrap_content”
        android:layout_below=“@+id/editTextValue2”
        android:layout_centerHorizontal=“true”
        android:layout_marginTop=“18dp”
        android:editable=“false”
        android:ems=“10” />
    <Button
        android:id=“@+id/buttonResult”
        android:layout_width=“wrap_content”
        android:layout_height=“wrap_content”
        android:layout_below=“@+id/editTextResult”
        android:layout_centerHorizontal=“true”
        android:layout_marginTop=“26dp”
        android:onClick=“onClickButtonResult”
        android:text=“Result” />
</RelativeLayout>

Manifest File

In the final step we wll put our service class entry (AddService in our case) in our project’s Manifest file like below.

<service android:name=”com.techblogon.aidlexample.AddService” />

 

<?xml version=“1.0” encoding=“utf-8”?>
<manifest xmlns:android=“http://schemas.android.com/apk/res/android”
    package=“com.techblogon.aidlexample”
    android:versionCode=“1”
    android:versionName=“1.0” >
    <usessdk
        android:minSdkVersion=“8”
        android:targetSdkVersion=“17” />
    <application
        android:allowBackup=“true”
        android:icon=“@drawable/ic_launcher”
        android:label=“@string/app_name”
        android:theme=“@style/AppTheme” >
        <activity
            android:name=“com.techblogon.aidlexample.AIDLActivity”
            android:label=“@string/app_name” >
            <intentfilter>
                <action android:name=“android.intent.action.MAIN” />
                <category android:name=“android.intent.category.LAUNCHER” />
            </intentfilter>
        </activity>
         <service android:name=“com.techblogon.aidlexample.AddService” />
    </application>
</manifest>

That’s it. Build and run the application. Enter 2 digits and click on Result button, you can get the result from the AIDL servie.

download

Leave a Reply

Your email address will not be published. Required fields are marked *