Android advanced AIDL uses custom types

Android advanced AIDL uses custom types

The original text was first published on the WeChat public account: Jianxingzhi

The previous article mainly introduced the use of AIDL and the communication between different processes in Android development. The remaining problem is how to use custom types in AIDL. The specific steps are as follows:

  1. Create a custom type
  2. Declare a custom type
  3. Define the business related to the custom type
  4. Rewrite business entity classes
  5. Remote call
  6. Verify AIDL

1. Create a custom type

What the custom type transmits is an entity object, and this entity class must implement the Parcelable interface, as follows:

// 
public class Work implements Parcelable {
    private String title;
    private String content;
    //getter setter Parcelable  
}
 

2. Declare a custom type

Create an .aidl file to declare the type just defined. Note that it is different from the specific business .aidl file. The declaration is as follows:

// .aidl 
package com.manu.aidldemo;
parcelable Work;
 

3. Define the business related to the custom type

Define the business related to the custom type in the .aidl file that defines the specific business, as follows:

//Declare any non-default types here with import statements
import com.manu.aidldemo.Work; //
interface IPersonAidlInterface {
    //
    Work getWorkInfo();
    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);
}
 

Note : Import the custom type, otherwise it will not be recognized.

4. Rewrite the business entity class

Because of the newly added specific business, that is, getWorkInfo(), the specific business needs to be implemented in the specific business class, as follows:

//
@Override
public Work getWorkInfo() throws RemoteException {
    Work work = new Work();
    work.setTitle(" AIDL");
    work.setContent("Android developer");
    return work;
}
 

5. Remote call

After successfully binding the Service, you will get the IBinder object, and then get the IPersonAidlInterface object through asInterface() to call it, as follows:

public void callRemoteClick(View view) {
    Log.i(TAG," ...");
    try {
        //
        Work work = iPersonAidlInterface.getWorkInfo();
        System.out.println(" title="+work.getTitle()+",content="+work.getContent());
    } catch (RemoteException e) {
        e.printStackTrace();
    }
}
 

6. Verify AIDL

The log running screenshot is as follows:

The use process has actually been explained clearly in the previous article. This article seems to be a bit redundant, but it is a summary of past knowledge!