Sunday, 29 December 2013

Android AIDL Example

Today I am going to show you how to create Android Interface Definition Language (AIDL) process. Each application in Android runs in its own process. An application cannot directly access the data of another application for security reasons. If you want access the data from another application then AIDL will help you to access those data. I have created two example one of Server which create the AIDL service and secondClient which acces the server data.
Server Example : 
1.) Create the aidl file on your package as following (IRemote.aidl).
1
2
3
4
5
6
7
    package com.example.aidlserver;
 
interface IRemote
{
  int add(int a, int b);
 
}
I have only created the add method on the interface IRemote
2.) Create the Service and Bind the IRemote Service as following
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.example.aidlserver;
 
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
 
public class ArithmeticService extends Service{
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return mBinder;
    }
    /**
     * IRemote defnition is available here
     */
    private final IRemote.Stub mBinder = new IRemote.Stub() {
 
        @Override
        public int add(int a, int b) throws RemoteException {
            // TODO Auto-generated method stub
            return (a + b);
        }
 
    };
}
3.) Mention the service to android manifest file as following
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?xml version="1.0" encoding="utf-8"?>
    package="com.example.aidlserver"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="7" />
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.aidlserver.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=".ArithmeticService"
                     android:process=":remote">
                <intent-filter >
                    <action android:name="com.remote.service.CALCULATOR"/>
                </intent-filter>
            </service>
    </application>
 
</manifest>
and also mention the action name that is important I mentioned “com.remote.service.CALCULATOR”
Client Example : 
1.) In the client example i show you how to access server data create. Create the same aidl package as you used in the server example  and create the same(copy) file as you created in the server example IRemote.aidl
2.) create the xml file (main.xml) as following
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
 
    <TextView android:id="@+id/resultText" android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
 
    <EditText android:id="@+id/firstValue" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:hint="Enter a numeric value"/>
 
    <EditText android:id="@+id/secondValue" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:hint="Enter a numeric value"/>
 
    <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content"
         android:weightSum="3">
 
    <Button android:id="@+id/add" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="Add" android:layout_weight="1"/>
 
    </LinearLayout>
 
    </LinearLayout>
3.) create the activity (MainActivity.java) as following
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package com.example.aidlclient;
 
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
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.EditText;
import android.widget.TextView;
import android.widget.Toast;
 
import com.example.aidlserver.IRemote;
 
public class MainActivity extends Activity implements OnClickListener  {
 
    EditText mFirst,mSecond;
    Button mAdd,mSubtract,mClear;
    TextView mResultText;
    protected IRemote mService;
    ServiceConnection mServiceConnection;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        mFirst = (EditText) findViewById(R.id.firstValue);
        mSecond = (EditText) findViewById(R.id.secondValue);
            mResultText = (TextView) findViewById(R.id.resultText);
        mAdd = (Button) findViewById(R.id.add);
        mAdd.setOnClickListener(this);
 
        initConnection();
 
    }
    void initConnection(){
        mServiceConnection = new ServiceConnection() {
 
                @Override
                public void onServiceDisconnected(ComponentName name) {
                    // TODO Auto-generated method stub
                    mService = null;
                    Toast.makeText(getApplicationContext(), "no", Toast.LENGTH_SHORT).show();
                    Log.d("IRemote", "Binding - Service disconnected");
                }
 
                @Override
                public void onServiceConnected(ComponentName name, IBinder service)
                {
                    // TODO Auto-generated method stub
                    mService = IRemote.Stub.asInterface((IBinder) service);
                    Toast.makeText(getApplicationContext(), "yes", Toast.LENGTH_SHORT).show();
                    Log.d("IRemote", "Binding is done - Service connected");
                }
            };
            if(mService == null)
            {
                Intent it = new Intent();
                it.setAction("com.remote.service.CALCULATOR");
                //binding to remote service
                bindService(it, mServiceConnection, Service.BIND_AUTO_CREATE);
            }
    }
    protected void onDestroy() {
 
        super.onDestroy();
        unbindService(mServiceConnection);
    };
 
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch(v.getId()){
        case R.id.add:{
            int a = Integer.parseInt(mFirst.getText().toString());
            int b = Integer.parseInt(mSecond.getText().toString());
 
            try{
                mResultText.setText("Result -> Add ->"+mService.add(a,b));
                Log.d("IRemote", "Binding - Add operation");
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        break;
      }
    }
}
I have created the service connection and create the IRemote aidl object to acces the data this will return addition of two numbers.
Output :

No comments:

Post a Comment