当前位置:   article > 正文

没掌握这些知识点也敢说自己熟悉AIDL?_android aidl封装

android aidl封装

AIDL介绍

AIDL全称Android Interface Definition Language 安卓接口定义语言,是Android开发中常用的一种跨进程通信的方式。

使用AIDL编写的文件是aidl文件,aidl文件在程序运行中并不起作用,起作用的是Android SDK工具基于aidl文件生成的Java语言的IBinder接口。这也意味着,你可以自定义IBinder接口来实现AIDL相同的效果。

AIDL的使用

Server端

创建.aidl文件

package com.example.android

interface IRemoteService {

    void setBookName(String name);

    int getBookId();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

AIDL 支持下列数据类型:
Java基本数据类型(如 int、long、char、boolean 等)、String、CharSequence、List、Map

实现接口

创建Binder类的实例,实现aidl中的方法

private final IRemoteService.Stub binder = new IRemoteService.Stub() {
    public int getBookId(){
        return 1;
    }
    public void setBookName(String aString) {
        // Does nothing
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

向客户端公开接口

通过Service的onBind方法,向客户端返回Binder对象。

public class RemoteService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // Return the interface
        return binder;
    }

    private final IRemoteService.Stub binder = new IRemoteService.Stub() {
        public int getBookId(){
            return 1;
        }
        public void setBookName(String aString) {
            // Does nothing
        }
    };
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

Client端

  1. 将客户端的.aidl文件复制到项目中
  2. 声明一个 IBinder 接口实例(基于 AIDL 生成)。
  3. 实现 ServiceConnection。
  4. 调用 Context.bindService(),从而传入您的 ServiceConnection 实现。
  5. 在 onServiceConnected() 实现中,您将收到一个 IBinder 实例(名为 service)。调用 YourInterfaceName.Stub.asInterface((IBinder)service),以将返回的参数转换为 YourInterface 类型。
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/265186
推荐阅读
相关标签
  

闽ICP备14008679号