第三部分:Android 应用程序接口指南---第一节:应用程序组件---第二章2-2.AIDL

第2-2章 AIDL

AIDL的全称为Android Interface Definition Language翻译过来为Android接口定义语言。它类似其他你可能用过的IDL。它允许在客户端和服务端你定义一致的程序接口,这样是为了彼此之间能使用IPC(进程间通讯)机制通讯。在android中,一个进程不能正常的访问另一个进程中的内存。他们需要把自己的对象分解为基本单位,操作系统才能理解它们,然后才能安排这些对象执行IPC。这样的写法会让代码冗余,所以android使用了AIDL机制来处理这个。使用AIDL的情况就是如果你允许客户端从不同的应用程序中以IPC机制访问你的service并且想要在serviece中处理多线程时,这样才需要使用AIDL。如果你不需要执行并发的IPC,那么你应该使用Binder接口,或者你想要执行IPC,但又不想处理多线程,那么可以使用Messenger。不管怎么样,你应该在理解第2-1章 Bound Service之后在来实现AIDL。

在你开始设计AIDL接口之前,应该先了解一下AIDL接口调用其实是直接的函数调用。你在本地进程中调用线程还是远程进程中调用线程会发生不同的情况。

  1. 在同一个被调用的线程中使用本地进程执行调用。如果这是你的主UI线程,那么它会继续在AIDL接口中执行。如果它是另外的线程,那么应该在service中用代码执行。因此,如果本地线程正在访问service,你能控制它们的执行(当然如果是另外的线程执行这种情况,我们不应该使用AIDL,而使用Binder)。
  2. 从一个远程进程中分发到你本地进程中的一个线程池,然后调用。你必须为未知线程中的被叫来电做准备,同时可能发生多次调用。换句话说,一个AIDL接口的实现必须是线程安全的。
  3. oneway关键字修改了远程调用的行为。当这个关键字被使用时,一个远程调用不会阻塞,它简单的发送事务处理数据并立即返回。这个接口的实现最终会收到一个从Binder线程池中的定期调用作来为一个正常的远程调用。如果oneway用于本地的一个调用,它不会影响到本地调用同步的问题。

2-2.1 定义一个AIDL接口 

你必须在.aidl文件中使用Java语法来定义一个AIDL接口,然后再src/目录下保存这个文件,并且在应用程序绑定service。当你编译每一个包含.aidl文件的应用程序时,Android SDK工具在.aidl文件中生成一个IBinder接口,并保存在项目的gen/目录下。service必须实现一个IBinder接口。客户端应用程序会绑定到service中并调用IBinder中的方法来执行IPC。为了创建一个绑定的service来使用AIDL,我们需要以下步骤:

1. 创建.aidl文件

这个文件定义的编程的接口

2. 实现接口

Android SDK工具使用Java语法在.aidl文件中生成一个接口。这个接口有一个叫Stub的内部抽象类,并且它继承自Binder并实现了AIDL接口中的方法。你必须继承自Stub类。

3. 暴露接口给客户端

实现一个Service并重写onBind()方法返回到Stub类的实现中。

2-2.1.1创建.aidl文件

AIDL使用一个简单的语法,让你使用一个或多个方法声明一个接口,并可以获得参数和返回值。参数和返回值可以是任意类型,甚至可以是其他AIDL生成的接口。每一个.aidl文件必须定义一个单一的接口。默认情况下,AIDL支持以下数据类型:所有基本数据类型(int,long,char,boolean等),String类型,CharSequence类型,List类型。Map类型。当然实际情况你使用ArrayList和HashMap也是可以的。还有一点你需要和其他类一样把包名和特定的improt给用上。并且不能使用static域。并且参数前比如加前缀,in,out或inout,默认的为in,例如 public void test(out int arg)

下面让我们来看一个例子,它是如何定义的,如代码清单2-2-1所示:

// IRemoteService.aidl

package com.example.android;

// 如果不是默认的类型你需要声明import的内容

/** 以下是示例的service接口*/

interface IRemoteService {
    /** 为这个service请求一个进程ID. */
    int getPid();
    /** 下面是一些基本类型参数,其实它使用了in前缀,由于in是默认的 不写就表示使用的是in前缀     */
    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);

}

 

代码清单2-2-1

简单的在你的src/目录中保存这个.aidl文件后,SDK工具会生成一个IBinder接口文件在你项目中的gen/目录中。生成的文件名和你自定义的.aidl文件名是一样的,只是自动生成的文件名后缀为.java了。例如src中IRemoteService.aidl,gen中为IRemoteService.java。

2-2.1.2实现这个接口

当你编译你的应用程序时,Android SDK工具会生成一个.java的文件,这个文件中包含一个Stub的子类,代码中一般会这么用:YourInterface.Stub。Stub也会定义一些助手方法,尤其是asInterface(),它获得一个IBinder(通常通过客户端的onServiceConnected()方法)并返回一个stub接口的实例。

为了从.aidl中实现这个生成的接口,继承生成的Binder接口并实现这个.aidl文件中的方法。一下是一个例子,客户端是如何调用代码清单2-2-1中定义的.aidl接口的。如代码清单2-2-2所示:

private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {

    public int getPid(){
        return Process.myPid();
    }
    public void basicTypes(int anInt, long aLong, boolean aBoolean,
        float aFloat, double aDouble, String aString) {
        //to do
    }

};

 

代码清单2-2-2

上面的代码中mBinder是Stub类(一个Binder)的一个实例,它为service定义了一个RPC(远程过程调用)接口。下一步,这个实例将暴露给客户端,这样就可以与service交互了。在你实现AIDL接口前,有一些规则你应该注意:

  1. 被叫来电不能保证一定是在主线程执行的,因此你需要考虑多线程,从最开始就妥善考虑你的service是线程安全的。
  2. 默认的,RPC调用是同步的。如果你知道service有一个时间稍微长点的请求,那么你不应该在Activity的主线程调用它,因为它可能会让你的程序中止(会弹出一个ANR对话框)。所以通常的做法是在客户端另起一个线程。
  3. 你抛出的异常都不会被发送回调用方

2-2.1.3 暴露接口给客户端

一旦你已经为service实现了接口,你就需要把接口暴露给客户端从而绑定。为了暴露接口,你需要写一个类继承自Service类并实现onBind方法,并且返回的就是你在客户端new的Stub实例。下面是一个暴露接口给客户端的例子,如代码清单2-2-3所示:

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

 

    @Override
    public IBinder onBind(Intent intent) {
        // 返回接口
        return mBinder;
    }

 

    private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
        public int getPid(){
            return Process.myPid();
        }
        public void basicTypes(int anInt, long aLong, boolean aBoolean,
            float aFloat, double aDouble, String aString) {
            // to do
        }
    };
}

 

代码清单2-2-3

现在,当一个客户端调用BindService()来连接service时,客户端的onServiceConnected()回调方法会接收到service中onBind()方法返回的mBinder实例。客户端必须也有能访问的接口,如果客户端和service都在不同的应用程序中,那么客户端应用程序必须复制.aidl文件在它的src/目录下。当客户端在onServiceConnected()中接收到IBinder回调时,它必须调用

YourServiceInterface.Stub.asInterface(service)强制转换返回的参数为YourServiceInterface类型。如代码清单2-2-4所示:

IRemoteService mIRemoteService;

private ServiceConnection mConnection = new ServiceConnection() {

    // 当service连接已建立时被调用

    public void onServiceConnected(ComponentName className, IBinder service) {

        // 以下的例子我们都是使用上面代码中的AIDL接口,获得一个IremoteInterface的实例,我们能用于在

        // service上调用

        mIRemoteService = IRemoteService.Stub.asInterface(service);

    }

    // 连接中断时被调用

    public void onServiceDisconnected(ComponentName className) {

        Log.e(TAG, "Service has unexpectedly disconnected");

        mIRemoteService = null;

    }

};

 

代码清单2-2-4

2-2.2 在IPC上传递对象

如果你有一个类想要通过IPC(跨进程调用)接口发送一些数据,你必须确定你类中的代码可被启动IPC通道利用,并且你的类应该支持Parcelable接口。支持Parcelable接口是很重要的,因为它允许Android系统分解对象为基本类型,这些基本类型能在跨进程中被打包。为了创建一个支持Parcelable协议的类,你必须做以下的工作:

  1. 让你的类实现Parcelable接口。
  2. 实现writeToParcel方法,获得当前对象的状态并写入到一个Parcel中。
  3. 添加一个CREATOR的静态域,它是一个接口,当你new它的时候,需要实现里面的方法。
  4. 最后,创建一个.aidl文件,用来声明你的parcelable类(就是下面的Rect.aidl文件)。如果你使用自定义的构建过程,而不添加.aidl文件。那么类似于C语言中的头文件一样,这个.aidl文件不会被编译。

AIDL在代码中使用这些方法和域,他打包与解包你的对象。例如这儿有一个Rect.aidl文件用于创建Rect类并使用了Parcelable接口,如代码清单2-2-5所示:

package android.graphics;
// 声明Rect,因此AIDL能找到它并知道它实现与parcelable协议
parcelable Rect;

 

代码清单2-2-4

以下是Rect类的实现,它实现了Parcelable协议,如代码清单2-2-5所示:

import android.os.Parcel;
import android.os.Parcelable;
 
public final class Rect implements Parcelable {
    public int left;
    public int top;
    public int right;
    public int bottom;
 
    public static final Parcelable.Creator<Rect> CREATOR = new
Parcelable.Creator<Rect>() {
        public Rect createFromParcel(Parcel in) {
            return new Rect(in);
        }
 
        public Rect[] newArray(int size) {
            return new Rect[size];
        }
    };
 
    public Rect() {
    }
 
    private Rect(Parcel in) {
        readFromParcel(in);
    }
 
    public void writeToParcel(Parcel out) {
        out.writeInt(left);
        out.writeInt(top);
        out.writeInt(right);
        out.writeInt(bottom);
    }
 
    public void readFromParcel(Parcel in) {
        left = in.readInt();
        top = in.readInt();
        right = in.readInt();
        bottom = in.readInt();
    }
}

 

代码清单2-2-5

打包Rect类是非常简单的。读和写的过程都是通过的Parcel来操作的。不要忘记从其他进程中的安全接收数据,这种情况下,Rect从Parcel中读取4个数据,但需要你用代码来保证这些值是可接受的范围,我们会在以后的权限章节中讲解在恶意软件中的安全问题。

2-2.3 调用一个IPC方法

下面是用AIDL定义的一个远程调用接口的步骤:

1. 在项目耳朵src/目录下包含.aidl文件。

2. 声明一个IBinder接口的实例(基于AIDL生成)

3. 实现ServiceConnection。

4. 在实现的ServiceConnection类中,调用Context.bindService()。

5. 在实现的ServiceConnection类中,你会接收到一个IBinder实例,调用

YourInterfaceName.Stub.asInterface((IBinder)service)来强制转换参数为YourInterfaceName类型。

  1. 你应该处理一个DeadObjectException异常,当连接断开时它会被抛出,并且仅通过远程方法抛出这个异常。
  2. 要断开连接,可以使用接口中的实例调用Context.unbindService()。调用一个IPC service有一些注意事项:

(1)  跨进程的对象引用计数

(2)  你能发送匿名对象作为一个方法的参数

下面是一个例子用来演示调用一个AIDL创建的service,来自ApiDemos中的Remote Service例子,如代码清单2-2-6所示:

public static class Binding extends Activity {
    /** 在service中调用的主要接口*/
    IRemoteService mService = null;
    /**在service中调用的另一个接口*/
    ISecondary mSecondaryService = null;
 
    Button mKillButton;
    TextView mCallbackText;
 
    private boolean mIsBound;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        setContentView(R.layout.remote_service_binding);
 
        // 注意按键点击事件传入的mBindListener
        Button button = (Button)findViewById(R.id.bind);
        button.setOnClickListener(mBindListener);
        button = (Button)findViewById(R.id.unbind);
        button.setOnClickListener(mUnbindListener);
        mKillButton = (Button)findViewById(R.id.kill);
        mKillButton.setOnClickListener(mKillListener);
        mKillButton.setEnabled(false);
 
        mCallbackText = (TextView)findViewById(R.id.callback);
        mCallbackText.setText("Not attached.");
    }
 
    /**
     * 用于和service的主接口交互的类
     */
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            // 当service的连接被建立时,会调用这个方法,参数中的这个IBinder对象可以用于和service交互
            // 我们通过一个IDL接口和我们的service通信,所以可以从原始service对象的中获得一个客户端的代表
            mService = IRemoteService.Stub.asInterface(service);
            mKillButton.setEnabled(true);
            mCallbackText.setText("Attached.");
 
            // 只要我们连上了我们就要监控service
            try {
                mService.registerCallback(mCallback);
            } catch (RemoteException e) {
                //处理异常问题 
            }
 
            // 我们要告诉用户,已经连接上了远程service
            Toast.makeText(Binding.this, R.string.remote_service_connected,
                    Toast.LENGTH_SHORT).show();
        }
 
        public void onServiceDisconnected(ComponentName className) {
            // 连接中断
            mService = null;
            mKillButton.setEnabled(false);
            mCallbackText.setText("Disconnected.");
 
             // 我们要告诉用户,已经连接中断了
            Toast.makeText(Binding.this, R.string.remote_service_disconnected,
                    Toast.LENGTH_SHORT).show();
        }
    };
 
    /**
     *用于和service的次要接口交互的类
     */
    private ServiceConnection mSecondaryConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            mSecondaryService = ISecondary.Stub.asInterface(service);
            mKillButton.setEnabled(true);
        }
 
        public void onServiceDisconnected(ComponentName className) {
            mSecondaryService = null;
            mKillButton.setEnabled(false);
        }
    };
 
    private OnClickListener mBindListener = new OnClickListener() {
        public void onClick(View v) {
            // 通过接口名绑定了两个service。通过远程service它允许其他应用被安装
            bindService(new Intent(IRemoteService.class.getName()),
                    mConnection, Context.BIND_AUTO_CREATE);
            bindService(new Intent(ISecondary.class.getName()),
                    mSecondaryConnection, Context.BIND_AUTO_CREATE);
            mIsBound = true;
            mCallbackText.setText("Binding.");
        }
    };
 
    private OnClickListener mUnbindListener = new OnClickListener() {
        public void onClick(View v) {
            if (mIsBound) {
                // 如果我们已经接收到service,是时候注销回调接口了
                if (mService != null) {
                    try {
                        mService.unregisterCallback(mCallback);
                    } catch (RemoteException e) {
                        // service崩溃了,这里也不需要做什么
                    }
                }
 
                unbindService(mConnection);
                unbindService(mSecondaryConnection);
                mKillButton.setEnabled(false);
                mIsBound = false;
                mCallbackText.setText("Unbinding.");
            }
        }
    };
 
    private OnClickListener mKillListener = new OnClickListener() {
        public void onClick(View v) {
      
            if (mSecondaryService != null) {
                try {
                    int pid = mSecondaryService.getPid();
                    Process.killProcess(pid);
                    mCallbackText.setText("Killed service process.");
                } catch (RemoteException ex) {
              
                    Toast.makeText(Binding.this,
                            R.string.remote_call_failed,
                            Toast.LENGTH_SHORT).show();
                }
            }
        }
    };
 
    private IRemoteServiceCallback mCallback = new IRemoteServiceCallback.Stub() {
        
        public void valueChanged(int value) {
            mHandler.sendMessage(mHandler.obtainMessage(BUMP_MSG, value, 0));
        }
    };
 
    private static final int BUMP_MSG = 1;
 
    private Handler mHandler = new Handler() {
        @Override public void handleMessage(Message msg) {
            switch (msg.what) {
                case BUMP_MSG:
                    mCallbackText.setText("Received from service: " + msg.arg1);
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
 
    };
}
 

代码清单2-2-6

 本文来自jy02432443,QQ78117253。是本人辛辛苦苦一个个字码出来的,转载请保留出处,并保留追究法律责任的权利

posted @ 2013-11-19 21:23  jy02432443  阅读(564)  评论(0编辑  收藏  举报