Introduction to AIDL in android

Foreword:

Today I looked at the basics and principles of AIDL. I encountered some problems during the learning process. I searched for many articles but did not get any solutions. Later I found the solution, so I will sort out the relevant knowledge here, take notes, and share it. Children's shoes for you.

overview:

This article mainly introduces the meaning, function and entry-level cases of AIDL. This article will also cover related knowledge such as Service and Binder. This article Without giving a detailed introduction, please find the information and study by yourself. The difference between transact and onTransact in Binder written by this master can be explained below:http://blog.csdn.net/sergeycao/article/details/52585411

1. What is AIDL

AIDL is one of the inter-process communication methods in Android, the abbreviation of Android interface definition language.

2. The role of AIDL

Inter-process communication is also called IPC (Inter-Process Communication). Because resources between processes cannot be shared, each system has its own set of IPC mechanisms. Android is an operating system based on the Linux kernel, but it does not inherit the IPC mechanism of Linux. , has its own set of IPC mechanisms. AIDL is a kind of IPC method. The bottom layer is based on the Binder mechanism. Its function is that your own APP can call methods in other APPs. It can be simply understood as binding the services of other APPs in your own APP, so that you can achieve and Interaction with other APPs.

3. AIDL implementation principle

Here is a brief introduction to how AIDL implements one APP calling the Service of another APP in Android. The client APP will bind a Service of the server APP through bindService, and then the Android system will call the onBinder method in this Service, which returns an IBinder object used to interact with the Service. bindService is executed asynchronously. The bindService method will return immediately, but it will not return IBinder to the client. The client APP must create a ServiceConnection object and pass it to bindService. ServiceConnection contains a callback method onServiceConnected. The system calls this and returns an IBinder object. The client APP uses this IBinder object to call Service.

4. Simple example

First create a server-side android project, create an AIDL file, right-click New->AIDL in the directory where MainActivity is located, enter the file name, and an AIDL file will be generated, as shown in the figure:


The basicTypes method explains what types are supported by default. Ignore it and define an interface method for calling:

interface IMyAidlInterface {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    /*void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);*/

    String getMessage();

}
Then sync project (very important) , Tools -> Android ->Sync project ***.

Now we create a new Service, which contains an internal class, inherits from the Stub class in AIDL just created, and implements the interface method. The onBinder method returns the object of the internal class.

public class MyService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    class MyBinder extends IMyAidlInterface.Stub{

        @Override
        public String getMessage() throws RemoteException {
            return "return success!";
        }

    }
}

Then register the implicit service and set the action in the AndroidManifest.xml file.

<service android:name=".MyService">
            <intent-filter >
                <action android:name="com.example.liujibin.testaidl1.MyService"></action>
            </intent-filter>
        </service>

The APP that provides services is now created. Then we create a new client APP, copy the AIDL file just created in the server APP to the client APP together with the entire aidl folder, and then sync project (very important) .


The package name of the AIDL file is the same as the package name of the AIDL file on the server.

Then we bind the server Service in the Activity in the client APP and call the implemented interface method.

public class MainActivity extends AppCompatActivity {

    private Button btn;
    private IMyAidlInterface iMyAidlInterface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn = (Button) findViewById(R.id.btn);

        Intent intent = new Intent();
        intent.setAction("com.example.liujibin.testaidl1.MyService");
        intent.setPackage("com.example.liujibin.testaidl1");
        bindService(intent,connection,BIND_AUTO_CREATE);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    Toast.makeText(MainActivity.this,""+iMyAidlInterface.getMessage(),Toast.LENGTH_SHORT).show();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            iMyAidlInterface = IMyAidlInterface.Stub.asInterface(iBinder);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            iMyAidlInterface = null;
        }
    };


}

I encountered a pitfall in the process. The Intent introduced in many basic tutorials only called setAction, so I had no problem running it on the android 4.4 system, but on android 5.0 the bindService reported an error and I needed to add a setPackage setting service. The package name of the terminal APP can be used normally. Because implicit startup is prohibited after Android 5.0, setPackage needs to be implemented.

Then install the server APP first, then run the client APP, click the button, success.


Guess you like

Origin blog.csdn.net/liujibin1836591303/article/details/53738612