Posts Tagged ‘AIDL’

Hello Droids,

As we all aware about RPC (Remote Procedure Call) in Java, right?

Lets do the same thing in Android, different name same functioning in way better 🙂
AIDL (Android Interface Definition Language)

Here I’m going to provide you step by step guidance for implementing AIDL in android.

Let’s Start a new project and named it as your favorite one for this demo.

  • Create on .aidl extension file, actually it is interface file so name it as IRemoteService.aidl
  • After creating this file add signature method in this file as follow,
// Declare the interface

interface IStringOperations {
    // You can pass values in, out, or inout.
    // Primitive datatypes (such as int, boolean, etc.) can only be passed in.
    String concat(in String value1, in String value2);
}
  • Now, create one Java file into the same package and extends it to Service.

e.g.,

public class StringOperations extends Service{

	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public IBinder onBind(Intent intent) {

		return mBinder;
	}

	/**
	 * @author Rahul Upadhyay
	 */
	private final IStringOperations.Stub mBinder = new IStringOperations.Stub() {
		/**
		 * Signature method which was declared in .aidl file will be coded here
		 * @author Rahul Upadhyay
		 */
		public String concat(String value1, String value2) throws RemoteException {
			return value1+ " "+ value2;
		}
	};

}
  • Now, create a client which will connect to this service with help of ServiceConnection, establishing ServiceConnection
/**
* @author Rahul Upadhyay
* ServiceConnection clsss to connect the service.
*/
	private ServiceConnection mServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {

			// Set null to service to unbind the object
			service = null;
			Log.d(TAG, "onServiceConnected() disconnected");
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder boundService) {

			//allocate the service to the interface
			service = IStringOperations.Stub.asInterface(boundService);
			Log.d(TAG, "onServiceConnected() connected");

		}
	};
  • Bind the service,
/**
* bindService will call the onServiceConnected method which will bind the Service with the current activity
*/
		boolean ret = bindService(new Intent(this, StringOperations.class),
				mServiceConnection, Context.BIND_AUTO_CREATE);

		Log.d(TAG, "initService() bound with " + ret);
    use the Service method which is declared in .aidl
service.concat("Rahul ", "Upadhyay")

Download the example from here