AIDL tutorial and AIDL tutorial

Source: Internet
Author: User
Tags mremote

AIDL tutorial and AIDL tutorial

Preface
Aidl is A method used for communication between Android processes. By using aidl, process A can call methods in Service of process B to implement data transmission and communication.

The following uses a simple instance to implement aidl communication step by step. This instance requires a Server project and a Client project. What we want to achieve is that the Client process can obtain data from the Server process.

Server implementation

Create a Server empty project and create an aidl file as follows:

After you enter the aidl file name, Android studio automatically places the aidl file in a folder with the same package name as the java file of the Android project ,:

The generated aidl file is named IMyAidlInterface. aidl. Its package name is example. hp. aidlserver, which is exactly the same as the package name of the java file.

Modify the content of the IMyAidlInterface. aidl file as follows:

Package example. hp. aidlserver; interface IMyAidlInterface {int getValue (); // custom abstract method for cilent process call}

Run the Server project and the IMyAidlInterface. java file is generated in the Build directory:

Open the IMyAidlInterface. java file and you can see the following Java class content,
The following code is automatically generated by the project:

package example.hp.aidlserver;public interface IMyAidlInterface extends android.os.IInterface {    /**     * Local-side IPC implementation stub class.     */    public static abstract class Stub extends android.os.Binder implements example.hp.aidlserver.IMyAidlInterface {        private static final java.lang.String DESCRIPTOR = "example.hp.aidlserver.IMyAidlInterface";        /**         * Construct the stub at attach it to the interface.         */        public Stub() {            this.attachInterface(this, DESCRIPTOR);        }        /**         * Cast an IBinder object into an example.hp.aidlserver.IMyAidlInterface interface,         * generating a proxy if needed.         */        public static example.hp.aidlserver.IMyAidlInterface asInterface(android.os.IBinder obj) {            if ((obj == null)) {                return null;            }            android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);            if (((iin != null) && (iin instanceof example.hp.aidlserver.IMyAidlInterface))) {                return ((example.hp.aidlserver.IMyAidlInterface) iin);            }            return new example.hp.aidlserver.IMyAidlInterface.Stub.Proxy(obj);        }        @Override        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_getValue: {                    data.enforceInterface(DESCRIPTOR);                    int _result = this.getValue();                    reply.writeNoException();                    reply.writeInt(_result);                    return true;                }            }            return super.onTransact(code, data, reply, flags);        }        private static class Proxy implements example.hp.aidlserver.IMyAidlInterface {            private android.os.IBinder mRemote;            Proxy(android.os.IBinder remote) {                mRemote = remote;            }            @Override            public android.os.IBinder asBinder() {                return mRemote;            }            public java.lang.String getInterfaceDescriptor() {                return DESCRIPTOR;            }            @Override            public int getValue() throws android.os.RemoteException {                android.os.Parcel _data = android.os.Parcel.obtain();                android.os.Parcel _reply = android.os.Parcel.obtain();                int _result;                try {                    _data.writeInterfaceToken(DESCRIPTOR);                    mRemote.transact(Stub.TRANSACTION_getValue, _data, _reply, 0);                    _reply.readException();                    _result = _reply.readInt();                } finally {                    _reply.recycle();                    _data.recycle();                }                return _result;            }        }        static final int TRANSACTION_getValue = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);    }    public int getValue() throws android.os.RemoteException;}

One of the Stub internal classes is very important. It is the key to implementing aidl communication. It inherits the Binder class and implements the IMyAidlInterface interface.

Next, we need to define a Service in the Server project for the Client process to call through bindService. This Service is created in the java directory and named MyService. class:

package example.hp.aidlserver;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.os.RemoteException;public class MyService extends Service {    IMyAidlInterface.Stub stub = new IMyAidlInterface.Stub() {        @Override        public int getValue() throws RemoteException {            return 99;        }    };    public MyService() {    }    @Override    public void onCreate() {        super.onCreate();    }    @Override    public IBinder onBind(Intent intent) {        return stub;    }}

We can see that an IMyAidlInterface. Stub object is returned in the onBind method of MyService. This object implements the getValue () method defined by the aidl interface, and the return value is 99.

Client implementation
Create a Client project and copy the aidl folder of the Server project to the Client project.Note that it is a full copy and no modification is required,The copied Client project structure is as follows:

Then we can get the Binder instance on the Server in the Client activity through the bindServer method, so that we can call the getValue () method. How can we do this? The following is the Client-side activity code. We can obtain data from the Server when the page is opened:

package example.hp.aidlclient;import android.app.Activity;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 example.hp.aidlserver.IMyAidlInterface;public class ClientMainActivity extends Activity {    private boolean mBound = false;    private static final String TAG = "MyService";    ServiceConnection connection = new ServiceConnection() {        @Override        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {            Log.d(TAG, "onServiceConnected");            mBound = true;            IMyAidlInterface iface = IMyAidlInterface.Stub.asInterface(iBinder);            try {                int value = iface.getValue();                Log.d(TAG, "get value: " + value);            } catch (RemoteException e) {                e.printStackTrace();            }        }        @Override        public void onServiceDisconnected(ComponentName componentName) {        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_client_main);        Intent intent = new Intent();        ComponentName componentName = new ComponentName("example.hp.aidlserver", "example.hp.aidlserver.MyService");        intent.setComponent(componentName);        bindService(intent, connection, BIND_AUTO_CREATE);    }    @Override    protected void onDestroy() {        super.onDestroy();        if (mBound) {            unbindService(connection);        }    }}

Run the Server first, then the Client, and then print the result as follows:

02-28 22:18:35.566 29647-29647/example.hp.aidlclient D/MyService: onServiceConnected02-28 22:18:35.566 29647-29647/example.hp.aidlclient D/MyService: get value: 99

It can be seen that the Client process has successfully obtained the data of the Server process.

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.