Monday 16 January 2012

AIDL (Remote Service Binding )


           If you want to access the service of different process /Application from your application then you need some IPC method because, In Android normally processes do not access other process memory.  Eg. User needs to user IPC method to access the Telephony Service. 


There are 2 method of IPC for Remote Service-
  1.        Messaging: - We will discuss this method in later posts.
  2.       AIDL (Android Interface Definition Language):-
In AIDL we create the .aidl file. This .aidl file contain an Interface containing methods those we want to access from our client application.  

Steps to use AIDL :-
  1. On Service side Create file with extension .aidl. In this file write an interface. Generally we keep this AIDL file in different package than the source file. Because the same AIDL file is needed in client side application. 
package com.aidl;

interface IRemoteInterface
{
      String getName();
      void setName(String a);
}

If we create the aidl in right way then eclipse automatically creates a java file in Gen folder.  This java file works as Interface between client and server.

2- Create the Service class

 package com.self; 
import com.aidl.IRemoteInterface; 
import android.app.Activity;
import android.app.Service;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class RemoteServer extends Service
{
      String userName;
      public void onCreate()
      {
            Log.i("RemoteServer","In onCreate");
      }
     
      public int onStartCommand(Intent intent, int flag, int statusID)
      {
            Log.i("RemoteServer","In onStartCommand");
            return START_STICKY;
      }
      @Override
      public IBinder onBind(Intent arg0) {
            // TODO Auto-generated method stub
           
            Log.i("RemoteServer","In onBind");
            return mBinder;
      }
     
      private IRemoteInterface.Stub mBinder = new IRemoteInterface.Stub() {
         @Override
            public String getName() throws RemoteException {
                  // TODO Auto-generated method stub
                  return userName.toUpperCase();
            }
             @Override
            public void setName(String a) throws RemoteException {
                  // TODO Auto-generated method stub
                  userName = a;
                 
            }
      };
}

Highlighted code shows the definition of AIDL interface methods. Here we set the String using setName() and get the same String in capital using getName(). 
As we can see when the client try to bind with service then onBind() returns the object of IRemoteInterface.stub object. This object is accessed in client side and using this mBinder object client access these two methods. 


3- In AndroidManifest.xml



    <service android:name = ".RemoteServer"
    android:process = ".remote">
    <intent-filter>
    <action android:name = "com.self.RemoteServer"></action>
    </intent-filter>
    </service>


4-  We copy same aidl file in client side in same package where it is created in Service side. Eg  com.aidl.


Folder Structure




5- Now write the Client side code. Where we start and bind with the service. Here we will create an Activity and call the startService() and bindService()

package com.lge;
import com.aidl.IRemoteInterface;
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.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class RemoteClient extends Activity {
    /** Called when the activity is first created. */
      Button start;
      IRemoteInterface serviceInterface;
      Context localContext;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        start = (Button)findViewById(R.id.startServer);
        localContext = this;
        start.setOnClickListener(new OnClickListener() {
                 
                  @Override
                  public void onClick(View v) {
                        // TODO Auto-generated method stub
                        startServ();
                        bindServ();
                  }
            });
    }
   
   private ServiceConnection conn = new ServiceConnection() {
           
            @Override
            public void onServiceDisconnected(ComponentName name) {
                  // TODO Auto-generated method stub
                 
            }
           
            @Override
public void onServiceConnected(ComponentName name, IBinder service) {
                  // TODO Auto-generated method stub
Log.i("RemoteClient","In onServicen binded...");
      try {

      serviceInterface = IRemoteInterface.Stub.asInterface(service);

      serviceInterface.setName("Zest of Android");
      Log.i("RemoteClient","User Name =”+serviceInterface.getName());
      Toast.makeText(localContext, ""+serviceInterface.getName(), Toast.LENGTH_SHORT).show();
      } catch (RemoteException e) {
                        // TODO Auto-generated catch block
            e.printStackTrace();
            }
      }
};
   
      private void bindServ() {
            // TODO Auto-generated method stub
            startService(new Intent("com.self.RemoteServer"));
      }

      private void startServ() {
            // TODO Auto-generated method stub
            bindService(new Intent("com.self.RemoteServer") , conn, Context.BIND_AUTO_CREATE);
      }

}

6-  When we bind the service the in onServiceConnected() we convert to reference of AIDL. And using this object we can call the Remote service methods.

This is how we bind our Application with remote Service.








5 comments:

  1. Your valuable comments are welcomed.

    ReplyDelete
  2. Thanks buddy. its was really helpful.

    ReplyDelete
  3. Thank, very helpful.
    Can you share more knowledge about Android?

    ReplyDelete
  4. Slots Online by Casino Experts | Deposit $5 Get $30
    If you have any doubts about slots 서울특별 출장마사지 online 광양 출장샵 casinos, check out 여주 출장샵 Casino 천안 출장샵 Experts reviews! We list 100+ slot games and their payouts so you 경주 출장샵

    ReplyDelete