AIDL is an interface definition language like other IDLs Languages. It support in Anroid the interface between two different process communication. It said remote method if a service in other application or process defines a method and client a using Activity or service. Remote method always are written in Android Service.
There are some simple steps to achieve this task:
- Create a aidl file.
package com.aidl.test;
interface IRemoteService {
int counter();
void printMyVal(String val);
}
As it will be saved the ADT plugin generate a java file in gen folder with its package name.
- Your remote service must implement these method
1- int counter();
2- void printMyVal(String val);
@Override
public IBinder onBind(Intent intent) {
return new IAdditionService.Stub() {
@Override
public int counter() throws RemoteException {
return counter;
}
@Override
public void printMyVal(String val){
System.out.println(val);
}
};
}
- From the client activity or service you should create a class which will implements ServiceConnection interface.
class RemoteServiceConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder aService) {
service = IRemoteService .Stub.asInterface(aService);
}
@Override
public void onServiceDisconnected(ComponentName name) {
service = null;
}
}
- You should create a method init, where you will initiate the connection and bind the remote service.
private void initService(){
connection = new AdditionServiceConnection();
Intent i = new Intent();
i.setClassName("com.aidl.test", com.aidl.test.AdditionService.class.getName());
boolean ret = bindService(i, connection, BIND_AUTO_CREATE);
Log.i("Create", "Bind service : "+ret);
}
- You need another method release where you release you connection with the service and make this connection null so memory can be freed.
private void releaseRemoteService(){
if(connection!=null){
unbindService(connection);
connection = null;
Log.i("Create", "Unbind Service");
}
}
- As you will call init method it create a connection and give an object of the service connection which is declare in RemoteServiceConnection method onServiceConnected.
- Through this object you can call all the remote methods.
- connection object should be RemoteSercieConnection method and Service object should be IRemoteService reference.
- onDestroy method you should call the realseRemoteService method.
Its so simple. :)
For further details you should go to http://developer.android.com/guide/developing/tools/aidl.html and read more about AIDL.
For further details you should go to http://developer.android.com/guide/developing/tools/aidl.html and read more about AIDL.