AIDL的使用步骤(即如何工作)

在弄清AIDL是如何使用Binder实现进程间通信的之前,我们应该要知道我们在使用AIDL的简要步骤

一、AIDL使用步骤

服务端:

  1. 创建对象Book.java,并实现Parcelable

  2. 新建AIDL文件(先随意命名否则报错),bookaidl.aidl,并在文件中声明Book类

  3. 新建AIDL接口文件IBookManager.aidl,并且在其中定义方法(注意ADIL文件导包)

  4. makeProject,系统自动于build文件夹下生成IBookManager.java

  5. 更改bookaidl.aidl为Book.aidl(要求必须与要传递对象同名,区分大小写)

  6. 创建继承Service的自定义服务AIDLService.java,并Manifest.xml中注册(注意:必须添加intent-filter,意义在于使其他进程可以找到此服务)

  7. 声明IBookManager.Stub类型变量(Binder类型),并实现接口方法(方法要使用同步方式)

  8. 重写onBind方法返回步骤7中的binder

客户端:

  1. 将服务端中AIDL文件夹移植到客户端(注意:包名一致)
  2. 声明IBookManager接口类型变量
  3. 声明ServiceConnection类型变量,并完成bindService
  4. 在serviceConnected方法中通过IBookManager.Stub.asInterface(service)获取IBookManager对象(应该要在子线程中调用)
  5. 这样就可以使用IBookManager对象调用服务端接口中的定义的方法了

项目结构

image.png
image.png

#代码一览
###服务端
/**
 * Created by Echo on 2019/5/14.
 * Action
 */
public class Book implements Parcelable {
    public int id;
    public String name;

    protected Book(Parcel in) {
        id = in.readInt();
        name = in.readString();
    }

    public static final Creator CREATOR = new Creator() {
        @Override
        public Book createFromParcel(Parcel in) {
            return new Book(in);
        }

        @Override
        public Book[] newArray(int size) {
            return new Book[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeString(name);
    }

    public String getName() {
        return name;
    }
}
// Book.aidl
package com.echo.mytts.aidl;

// Declare any non-default types here with import statements
parcelable Book;

// IBookManager.aidl
package com.echo.mytts.aidl;

// Declare any non-default types here with import statements
import com.echo.mytts.aidl.Book;

interface IBookManager {
    /**
     * 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);
    List getBookList();
    void addBook(in Book book);

}
/**
 * Created by Echo on 2019/5/14.
 * Action
 */
public class AIDLService extends Service {
    private List mBookList = new ArrayList<>();


    private IBookManager.Stub iBookManager = new IBookManager.Stub() {
        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

        }

        @Override
        public List getBookList() throws RemoteException {
            synchronized (mBookList){
                Log.i("service","查看了图书"+mBookList.size());
                return mBookList;
            }

        }

        @Override
        public void addBook(Book book) throws RemoteException {
            synchronized (mBookList){
                mBookList.add(book);
                Log.i("service","添加了图书"+ book.getName());
            }

        }
    };


    @Override
    public IBinder onBind(Intent intent) {

        return iBookManager;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("service","onCreate");
    }

客户端

public class MainActivity extends AppCompatActivity {
    private IBookManager bookManager;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("client","连接service成功");
            bookManager = IBookManager.Stub.asInterface(service);

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("client","取消连接");

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.option).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bookManager == null)
                    return;
                try {
                    Log.i("client","发起添加图书请求");
                    bookManager.addBook(new Book(99,"AIDL"));
                    Log.i("client","发起查看图书请求");
                    bookManager.getBookList();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent();
        intent.setAction("com.echo.mytts.aidl");
        intent.setPackage("com.echo.mytts");
        bindService(intent,serviceConnection,Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unbindService(serviceConnection);
    }

你可能感兴趣的:(AIDL的使用步骤(即如何工作))