zoukankan      html  css  js  c++  java
  • AIDL简单使用

    1.AIDL定义

      AIDL是android interface definition language的缩写,它对android IPC组件Binder进行了封装。使用它不需理会底层IPC的实现,只需要简单的定义接口,然后ADT编译生成IPC需要的java文件。极大的方便了开发者和提升了开发的速度及规范。

    2.AIDL的使用

      AIDL使用很简单,只需要三个步骤:

      1)接口的定义

      在aidl文件中定义需要给远程调用的接口,它会被ADT自动编译成java文件

      2)接口的实现

      接口定义好了,需要实现接口

     1     /**
     2      * A secondary interface to the service.
     3      */
     4     private final ISecondary.Stub mSecondaryBinder = new ISecondary.Stub() {
     5         public int getPid() {
     6             return Process.myPid();
     7         }
     8         public void basicTypes(int anInt, long aLong, boolean aBoolean,
     9                 float aFloat, double aDouble, String aString) {
    10         }
    11     };

       实现好接口后,还需要定义Service,实现它的 onBind 方法,然后在onBind方法中将实现的 binder 对象返回,供远程客户端调用。

      3)接口的调用

      首先在客户端绑定远程服务:

    1 bindService(new Intent(ISecondary.class.getName()),
    2                         mSecondaryConnection, Context.BIND_AUTO_CREATE);

      然后实现ServiceConnecton接口,在绑定成功后将远端Service的binder 对象返回:

     1         /**
     2          * Class for interacting with the secondary interface of the service.
     3          */
     4         private ServiceConnection mSecondaryConnection = new ServiceConnection() {
     5             public void onServiceConnected(ComponentName className,
     6                     IBinder service) {
     7                 // Connecting to a secondary interface is the same as any
     8                 // other interface.
     9                 mSecondaryService = ISecondary.Stub.asInterface(service);
    10                 mKillButton.setEnabled(true);
    11             }
    12 
    13             public void onServiceDisconnected(ComponentName className) {
    14                 mSecondaryService = null;
    15                 mKillButton.setEnabled(false);
    16             }
    17         };

      最后直接调用之前定义好的接口即可

  • 相关阅读:
    H5版俄罗斯方块(5)---需求演进和产品迭代
    vim 常用 NERDTree 快捷键
    C和C++中include 搜索路径的一般形式以及gcc搜索头文件的路径
    MySQL复制协议
    深入解析MySQL replication协议
    Install CodeBlocks in CentOS 7
    Impala 源码分析-FE
    Elasticsearch 6.x 的分页查询数据
    1、树莓派3B开箱+安装系统
    Python创建ES索引
  • 原文地址:https://www.cnblogs.com/pillowzhou/p/4909272.html
Copyright © 2011-2022 走看看