Android Interface Definition Language (AIDL) Example

By Arvind Rai, July 22, 2015
This page will provide Android Interface Definition Language (AIDL) example. AIDL facilitates to communicate between server and client. In android we cannot access memory from one process to another process. If we want to do, we can do it via primitives that operating system can understand. Android facilitates us to do this task via AIDL. Here on this page, we will provide server and client app. Both will be agree on a (.aidl) file which will be same for server and client both. Client will communicate with server using the methods defined in .aidl file.

Create AIDL Server

We will create server app which will serve to the client app. For the example, server will have two methods. First one will accept two numbers and return the multiplication. Second method will accept name and return message with name.

Server Project Structure in Eclipse

Android Interface Definition Language (AIDL) Example

Create Interface with (.aidl) Extension

Create an (.aidl) file in which we will create interface with required methods. These methods will support int, long, char, Boolean , String, CharSequence, List and Map datatypes.
ICalService.aidl
package com.concretepage;
interface ICalService {
	String getMessage(String name);
	int getResult(int val1, int val2);
} 

Implement Interface Stub within Service

Implement Interface stub within service and define methods.
CalService.java
package com.concretepage;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
public class CalService extends Service {
	@Override
	public IBinder onBind(Intent arg0) {
		return binder;
	}
	private final ICalService.Stub binder = new ICalService.Stub() {
		@Override
		public int getResult(int val1, int val2) throws RemoteException {
			return val1 * val2;
		}
		@Override
		public String getMessage(String name) throws RemoteException {
			return "Hello "+ name+", Result is:";
		}
	};
} 

Create Main Activity

Create main activity.
MainActivity.java
package com.concretepage;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	}
} 

AndroidManifest.xml: Configure Service

In AndroidManifest.xml, configure service.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.concretepage"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="20" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name">
        <activity 
            android:name="com.concretepage.MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="com.concretepage.CalService" android:process=":remote">
            <intent-filter>
                <action android:name="multiplyservice"/>
            </intent-filter>
        </service>
    </application>
</manifest> 
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#C98C00"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/msg" 
        android:textSize="25sp"/>
</LinearLayout> 

Create AIDL Client

Client will connect to server by using bindService() method and then will call methods given in server AIDL interface.

Client Project Structure in Eclipse

Android Interface Definition Language (AIDL) Example

Use Server AIDL file

Copy server .aidl file here in the client.
ICalService.aidl
package com.concretepage;
interface ICalService {
	String getMessage(String name);
	int getResult(int val1, int val2);
} 

Main Activity to Interact with Server

Now create main activity in which we will create ServiceConnection to bind with server service.
MainActivity.java
package com.concretepage.client;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.concretepage.ICalService;
public class MainActivity extends Activity {
    EditText editName, editVal1, editVal2;
    TextView resultView;
    protected ICalService calService = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main);
    }
    @Override
    protected void onStart() {
        super.onStart();
        editName = (EditText)findViewById(R.id.name);
        editVal1 = (EditText) findViewById(R.id.num1);
        editVal2 = (EditText) findViewById(R.id.num2);
        resultView = (TextView) findViewById(R.id.result);
		if (calService == null) {
			Intent it = new Intent("multiplyservice");
			bindService(it, connection, Context.BIND_AUTO_CREATE);
		}
    }
    @Override	    
    protected void onDestroy() {
	super.onDestroy();
	unbindService(connection);
    }
    public void multiply(View v) {
	switch (v.getId()) {
		case R.id.multiply_btn: {
			int num1 = Integer.parseInt(editVal1.getText().toString());
			int num2 = Integer.parseInt(editVal2.getText().toString());
			try {
				int result = calService.getResult(num1, num2);
				String msg = calService.getMessage(editName.getText().toString());
				resultView.setText(msg + result);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
			break;
		}
	}
    }
    private ServiceConnection connection = new ServiceConnection() {
	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
		calService = ICalService.Stub.asInterface(service);
		Toast.makeText(getApplicationContext(),	"Service Connected", Toast.LENGTH_SHORT).show();
	}
	@Override
	public void onServiceDisconnected(ComponentName name) {
		calService = null;
		Toast.makeText(getApplicationContext(), "Service Disconnected", Toast.LENGTH_SHORT).show();
	}
   };
} 
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#C98C00"
    tools:context=".MainActivity">
    <EditText
	    android:id="@+id/name"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:hint="@string/name_hint"
	    android:inputType="text" />
    <EditText
	    android:id="@+id/num1"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:hint="@string/num1_hint"
	    android:inputType="number" />
    <EditText
	    android:id="@+id/num2"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:hint="@string/num2_hint"
	    android:inputType="number" />
    <Button
        android:id="@+id/multiply_btn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/btn_msg"
        android:onClick="multiply" />
    <TextView
        android:id="@+id/result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"/>
</LinearLayout> 
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.concretepage.client"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="20" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name">
        <activity
            android:name="com.concretepage.client.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest> 

Output

Android Interface Definition Language (AIDL) Example

Download Server Source Code

Download Client Source Code

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us