• 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         };

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

  • 相关阅读:
    macOS 修改键盘重复按键延迟
    stdout 与 stderr 区别
    E. 1-Trees and Queries
    Codeforces Round #615 (Div. 3)
    Codeforces Round 613(div 2)
    Codeforces Edu80
    SPOJ
    快读
    《货车运输》题解--最大生成树&倍增
    倍增思想求lca
  • 原文地址:https://www.cnblogs.com/pillowzhou/p/4909272.html
Copyright © 2020-2023  润新知