aidl的一个简单demo

demo目的:写两个简单demo,Client和Server,Server提供计算两数之和的服务,Client去调用Server的服务。

1.demo实现流程

aidl.png

2.具体代码

2.1 Server端

1.编写aidl文件

// Declare any non-default types here with import statements

interface ISimpleService {
    /**
     * 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);

    int sum(int a, int b);

}

basicTypes这个方法是自动生成的,其实不注释了也没关系,不用管它。

2.在Server端rebuild

rebuild后,会自动生成一个接口文件,名称和编写的aidl文件名称一样,路径:build/generated/aidl_source_output_dir/debug/out/cn/maoqingbo/aidlserver/ISimpleService.java

3.创建Service,new一个Stub对象,并在onBind方法中返回

这几步都在Service中,直接贴下Service的代码吧,比较简单

public class SimpleService extends Service {

    private static final String TAG = "SimpleService";

    public SimpleService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind: ");
        return stub;
    }

    private ISimpleService.Stub stub = new ISimpleService.Stub() {
        @Override
        public int sum(int a, int b) {
            Log.d(TAG, "sum: ");
            return a+b;
        }
    };

}

2.2 Client端

1.拷贝Server端的aidl代码

由于这个demo比较简单,自己再写一遍也没关系,但是还是建议拷贝,因为我刚开始在服务端将BasicTypes那个方法注释了,在客户端却没有注释,导致死活连接不到Service,不信邪的可以试试。

注意的是,AS自动会搞一个aidl的文件夹,跟java那个文件夹平级,这样就挺好,不要自己去改目录结构。

2.rebuild下

3.绑定Server端的Service

这事首先要准备好一个接口对象,等会在bindService时给传过去

private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            iSimpleService = ISimpleService.Stub.asInterface(service);
            isConnected = true;
            Log.d(TAG, "Connection succeeded!");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isConnected = false;
            Log.d(TAG, "Connection failed!");
        }
    };

然后,这时候就要bindService了

Intent intent = new Intent();
        intent.setClassName("cn.mao.aidlserver",
                "cn.mao.aidlserver.SimpleService");
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);

4.调用Server服务

这是最后一步了,我们声明一个接口(第2步之后AS自动生成的)对象,那问题来了,这个对象什么初始化呢,其实就是在第3步的回调中,如果连接成功,会给它初始化。

3.demo效果

demo效果.jpg

看了下,没算错。源码不贴了,比较简单。

4.bind不成功问题

刚开始我的demo的targetsdk是31,始终不能绑定成功,于是换成29是ok的,30不行,网上找了很久,原来是在Android11(Api level 30)上要求在Manifest中添加下面的属性才可以:

<queries>
        <package android:name="cn.maoqingbo.aidlserver" />
    </queries>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容