Android: Use AIDL to implement inter-process communication (see the example for source code download)

Source: Internet
Author: User
Tags mremote

For the AIDL introduction and implementation steps, refer:

Http://www.cnblogs.com/hibraincol/archive/2011/09/06/2169325.html

This article uses an example to analyze the implementation of AIDL.

In this example, the AIDL client obtains the webPage information provided by the AIDL server through the AIDL interface. The following describes the implementation steps of AIDL communication:

I. Write server code

1. First write the AndroidManifest. xml file:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="com.braincol.aidl.service"      android:versionCode="1"      android:versionName="1.0">    <uses-sdk android:minSdkVersion="8" />    <application android:icon="@drawable/icon" android:label="@string/app_name">    <service android:name="RemoteService">        <intent-filter>            <action android:name="com.braincol.aidl.remote.webpage"/>        </intent-filter>    </service>    </application></manifest>

 

The server package name is com. braincol. aidl. service, and the server only needs one service component to provide the AIDL service. The Service component name is RemoteService, which is a subclass of the service to be implemented. <Action android: name = "com. braincol. aidl. remote. webpage "/>, specified action name as" com. braincol. aidl. remote. webpage ", the client finds and connects to the server through the action name.

2. Create the RemoteWebPage. aidl file.

Create the RemoteWebPage. aidl file under the package com. braincol. aidl. service:

package com.braincol.aidl.service; interface RemoteWebPage {    String getCurrentPageUrl();     }

You can see that the content is very simple. This file contains a RemoteWebPage interface, and the interface only contains the getCurrentPageUrl () method. The following client will use the getCurrentPageUrl () provided here () method to obtain the desired information.

3. Generate the RemoteWebPage. java File

Save and compile the project (compiled in eclipse). A RemoteWebPage. java file is displayed in the com. braincol. aidl. service package under the gen/directory:

/* * This file is auto-generated.  DO NOT MODIFY. * Original file: F:\\workspace\\android\\AIDL-simple\\AIDLService\\src\\com\\braincol\\aidl\\service\\RemoteWebPage.aidl */package com.braincol.aidl.service;public interface RemoteWebPage extends android.os.IInterface{    /** Local-side IPC implementation stub class. */    public static abstract class Stub extends android.os.Binder implements com.braincol.aidl.service.RemoteWebPage    {        private static final java.lang.String DESCRIPTOR = "com.braincol.aidl.service.RemoteWebPage";        /** Construct the stub at attach it to the interface. */        public Stub()        {            this.attachInterface(this, DESCRIPTOR);        }        /**         * Cast an IBinder object into an com.braincol.aidl.service.RemoteWebPage interface,         * generating a proxy if needed.         */        public static com.braincol.aidl.service.RemoteWebPage asInterface(android.os.IBinder obj)        {            if ((obj==null)) {                return null;            }            android.os.IInterface iin = (android.os.IInterface)obj.queryLocalInterface(DESCRIPTOR);            if (((iin!=null)&&(iin instanceof com.braincol.aidl.service.RemoteWebPage))) {                return ((com.braincol.aidl.service.RemoteWebPage)iin);            }            return new com.braincol.aidl.service.RemoteWebPage.Stub.Proxy(obj);        }        public android.os.IBinder asBinder()        {            return this;        }        @Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException        {            switch (code)            {            case INTERFACE_TRANSACTION:            {                reply.writeString(DESCRIPTOR);                return true;            }            case TRANSACTION_getCurrentPageUrl:            {                data.enforceInterface(DESCRIPTOR);                java.lang.String _result = this.getCurrentPageUrl();                reply.writeNoException();                reply.writeString(_result);                return true;            }            }            return super.onTransact(code, data, reply, flags);        }        private static class Proxy implements com.braincol.aidl.service.RemoteWebPage        {            private android.os.IBinder mRemote;            Proxy(android.os.IBinder remote)            {                mRemote = remote;            }            public android.os.IBinder asBinder()            {                return mRemote;            }            public java.lang.String getInterfaceDescriptor()            {                return DESCRIPTOR;            }            public java.lang.String getCurrentPageUrl() throws android.os.RemoteException            {                android.os.Parcel _data = android.os.Parcel.obtain();                android.os.Parcel _reply = android.os.Parcel.obtain();                java.lang.String _result;                try {                    _data.writeInterfaceToken(DESCRIPTOR);                    mRemote.transact(Stub.TRANSACTION_getCurrentPageUrl, _data, _reply, 0);                    _reply.readException();                    _result = _reply.readString();                }                finally {                    _reply.recycle();                    _data.recycle();                }                return _result;            }        }        static final int TRANSACTION_getCurrentPageUrl = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);    }    public java.lang.String getCurrentPageUrl() throws android.os.RemoteException;}

This file is automatically generated by the Android SDK Tool Based on RemoteWebPage. aidl. Do not try to modify this file (it is also changed ). The RemoteWebPage Interface contains an abstract internal class named Stub, which declares RemoteWebPage. the getCurrentPageUrl () method described in aidl also defines a small number of helper methods. Stub also defines a small number of helper methods, especially asInterface (), use it or obtain IBinder (when applicationContext. when bindService () is successfully called, it is passed to the onServiceConnected () of the client and an interface instance used to call the IPC method is returned. For more details, seeCalling an IPC Method.

4. Compile RemoteService. java

To implement AIDL communication, you must implement the RemoteWebPage. Stub interface in the RemoteService class, and then the related methods in RemoteWebPage. Stbu. The following is the code of RemoteService. java:

Package com. braincol. aidl. service; import android. app. service; import android. content. intent; import android. OS. IBinder; import android. OS. remoteException; import android. util. log;/***** @ author briancol * @ description provides service **/public class RemoteService extends Service {private final static String TAG = "RemoteService "; @ Override public IBinder onBind (Intent intent) {Log. I (TAG, "OnBind"); return new MyBinder ();} private class MyBinder extends RemoteWebPage. stub {@ Override public String getCurrentPageUrl () throws RemoteException {return "http://www.cnblogs.com/hibraincol ";}}}

In this way, MyBinder is a subclass of the RemoteWebPage. Stub class, so that you can expose the AIDL interface (MyBinder) to the client through RemoteService ). Now, if the client (such as an Activity) calls bindService () to connect to this server (RemoteService), The onServiceConnected () callback function of the client will obtain the onBind () from the server (RemoteService () the returned MyBinder object.

Here we will summarize the writing process of the server:

1. Create a. aidl file:

This file (YourInterface. aidl) defines available client methods and data interfaces

2. implement this interface:

The Android SDK will generate an aidl interface based on your. AIDL file. The generated interface contains an abstract internal class named Stub, which declares all. the methods described in aidl must inherit and implement the Stub class in the code. the method defined in aidl.

3. Publish the server interface to the client:

Implement a Service and return the sub-class (Implementation class) of the Stub class implemented in step 1 in the onBinder method ).

 

Now, the server code is compiled. Next, write the client.

2. Write client code

Because the client and the server are not in the same process (application), the client must have the same copy as the server under the src/directory. aidl file copying (this also means that the package name, class name, and content are identical, and the client's. the aidl file is understood as a proxy), so that the client will use this RemoteWebPage. the aidl file generates the same RemoteWebPage as the server under the gen/object. java file, and then the client can access the methods provided by the server through this interface. The following is the client's code:

Package com. braincol. aidl. 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. util. log; import android. view. view; import android. view. view. onClickListener; import android. widget. butt On; import android. widget. textView; import com. braincol. aidl. service. remoteWebPage; public class ClientActivity extends Activity implements OnClickListener {private final static String TAG = "ClientActivity"; TextView textView; Button btn_bind; Button btn_getAllInfo; String actionName = "com. braincol. aidl. remote. webpage "; RemoteWebPage remoteWebPage = null; String allInfo = null; boolean isBinded = fals E; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); textView = (TextView) findViewById (R. id. textView); btn_bind = (Button) findViewById (R. id. btn_bind); btn_getAllInfo = (Button) findViewById (R. id. btn_allinfo); btn_getAllInfo.setEnabled (false); btn_bind.setOnClickListener (this); btn_getAllInfo.setOnClickListener (this );}@ Override protected void onPause () {super. onPause (); Log. d (TAG, "onPause"); if (isBinded) {Log. d (TAG, "unbind"); unbindService (connection) ;}} private class MyServiceConnection implements ServiceConnection {@ Override public void onServiceConnected (ComponentName, IBinder service) {Log. I (TAG, "establish connection... "); remoteWebPage = RemoteWebPage. stub. asInterface (service); if (remoteWebPage = null) {textView. se TText ("bind service failed! "); Return;} try {isBinded = true; btn_bind.setText (" disconnected "); textView. setText (" connected! "); AllInfo = remoteWebPage. getCurrentPageUrl (); btn_getAllInfo.setEnabled (true);} catch (RemoteException e) {e. printStackTrace () ;}@ Override public void onServiceDisconnected (ComponentName name) {Log. I (TAG, "onServiceDisconnected... ") ;}} MyServiceConnection connection = new MyServiceConnection (); @ Override public void onClick (View v) {if (v = this. btn_bind) {if (! IsBinded) {Intent intent = new Intent (actionName); bindService (intent, connection, Context. BIND_AUTO_CREATE);} else {Log. I (TAG, "disconnect... "); unbindService (connection); btn_getAllInfo.setEnabled (false); btn_bind.setText (" connection "); isBinded = false; textView. setText ("disconnected! ") ;}} Else if (v = this. btn_getAllInfo) {textView. setText (allInfo );}}}

 

In the above Code, MyServiceConnection implements the ServiceConnection class. In the onServiceConnected method of MyServiceConnection class, RemoteWebPage is used. stub. asInterface (service) obtains the RemoteWebPage interface object of the remote server, so that the remoteWebPage can be used. getCurrentPageUrl () obtains the information provided by the server. The client binds the remote server through the bindService () method and disconnects the server through the unbindService () method. The code for connecting to the client is:

    Intent intent  = new Intent(actionName);    bindService(intent, connection, Context.BIND_AUTO_CREATE);

The client finds the server through actionName (com. braincol. aidl. remote. webpage.

Below is a summary of the client writing process:

1. Include the. adil file in the src/directory.

2. DeclareIBinderInterface (generated through the. aidl file) instance.

3. ImplementationServiceConnection.

4. CallContext. bindService () bind your ServiceConnection implementation Class Object (that is, remote server ).

5. InonServiceConnected()Method will receive the IBinder object (that is, the server), callYourInterfaceName.Stub.asInterface((IBinder)service)Convert the return valueYourInterfaceType.

6. Call the methods defined in the interface and always catch the DeadObjectException exception thrown when the connection is interrupted. This is the only exception that may be thrown by the remote method.

7. CallThe Context. unbindService () method is disconnected.

 

The following shows the source code of this example:

Http://download.csdn.net/detail/Niosm/3593187

In the example with a slightly more complex point (Parcelable object is passed through IPC ):

Http://download.csdn.net/detail/Niosm/3593376

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.