AIDL(Android接口定义语言)允许你定义编程接口来让服务器和客户端进行进程间通信。在Android中,一个进程无法访问另外一个进程的内存。所以他们需要分解成原始对象,让操作系统能够理解,并跨过界限来处理对象。写这些处理代码非常麻烦,所以Android使用AIDL帮你处理。
提示:只有在允许客户端从不同程序访问服务器并进行进程间通信和需要处理多线程时才需要使用AIDL,如果不需要在不同的程序间执行并发的IPC,你可以通过实现一个Binder来实现,或者如果你想执行IPC,但是不需要处理多线程,那么使用Messenger就够了。
在设计的AIDL前,你需要知道调用一个AIDL接口就是直接函数调用。你不需要知道线程是在哪个调用产生的,一个本地进程产生的线程和远程进程产生的线程有什么区别,特别指出:
  • 从本地进程调用的话就是在相同的线程中被执行。如果是UI主线程,那么这个线程就继续执行AIDL接口,如果是其他线程,那么就是服务器在执行你的代码。因此,如果仅仅是本地线程访问服务,你可以完全控制线程的执行(不过如果是这种情况的话,你不应该使用AIDL,而是创建一个Binder的实现)。
  • 从远程进程调用的话,会被从一个线程池派遣,平台维持这个线程池在你的进程中。你需要做好处理同时被多个未知线程调用的准备,也就是说,要实现线程安全。
  • 远程调用修改行为是单向的。但使用时,一个远程调用不会堵塞,它简单的发送交互数据,然后马上返回。接口的实现最终是有规律的从Binder线程池中被调用。如果单向通道被用在本地调用中,不会有任何影响,调用也还是同步的。
定义一个AIDL接口 你必须定义你的AIDL接口在一个.aidl文件中,使用的是Java的语法,并保存在拥有服务器的程序源代码目录和需要绑定服务器的其他程序的源代码目录中。
当你创建包含.aidl文件的程序,Android SDK工具会基于.aidl文件生成IBinder接口,并保存在项目的gen/目录下。
使用AIDL创建一个受绑定的服务器需要下面这些步骤:
  1. 创建.aidl文件
  2. 实现接口
    SDK工具基于.aidl文件生成一个java语言的接口。这个接口有一个内部抽象类,名称是Stub,它继承Binder,从AIDL接口中实现方法。你需要继承Stub类,实现里面的函数。
  3. 展示接口给客户端
    实现一个Service,重写onBind()方法,返回一个Stub类的实现。
1. 创建.aidl文件 AIDL使用简单的语法让你声明一个接口,接口包含一个或者多个可以传递参数和返回值的函数。参数和返回值可以是任何类型。
.aidl文件使用java语言构造,每个.aidl文件必须定义一个单一的接口,并且只包含接口声明和函数签名。
默认AIDL支持下面这些数据类型:
  • java语言的基本类型(int, long, char, boolean等)
  • String
  • CharSequence
  • List
  • Map
使用其他类型需要用import声明,即使被定义在接口相同的包中也一样。
当定义你的service接口时,你需要知道:
  • 函数可以携带0个或者多个参数,返回一个值,或者不返回值。
  • 所有非初始参数都需要一个方向标志来指明数据流向,in, out或者inout。 默认是in。
  • 代码注释会被包含到生成的IBinder接口。
  • 只支持函数,不能包含静态成员在AIDL中。
这是一个.aidl文件的例子:
// IRemoteService.aidlpackage com.example.android;// Declare any non-default types here with import statements/** Example service interface */interface IRemoteService {    /** Request the process ID of this service, to do evil things with it. */    int getPid();    /** 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);}
保存.aidl文件在src/目录,SDK工具会生成一个同名的.java文件。
2. 实现接口 生成的java文件包含一个名为Stub的子类,它是父类接口的抽象实现,并且声明了.aidl文件中的所有函数。
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) {        // Does nothing    }};
现在mBinder就是Stub类的实现。
这里有一些实现AIDL的规则:
  • 内部调用不能保证被执行在主线程上,所以你需要考虑多线程的启动和线程安全的创建你的service。
  • 默认情况下,RPC调用时同步的,如果service需要执行一段时间,你就不应该再主线程调用它
  • 不会抛出异常给调用者。
3. 展示接口给客户端 如果你已经实现了服务器接口,那么你需要展示它给客户端绑定。需要继承Service,实现onBind()方法来返回Stub的实例:
public class RemoteService extends Service {    @Override    public void onCreate() {        super.onCreate();    }    @Override    public IBinder onBind(Intent intent) {        // Return the interface        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) {            // Does nothing        }    };}
由于客户端也需要方法接口类,所以如果客户端和服务器不在一个程序的话,你就需要复制.aidl文件到客户端的src/目录下。
当客户端在onServiceConnected()中接收到IBinder时,你需要调用YourServiceInterface.Stub.asInterface(service)来返回YourServiceInterface类型:
IRemoteService mIRemoteService;private ServiceConnection mConnection = new ServiceConnection() {    // Called when the connection with the service is established    public void onServiceConnected(ComponentName className, IBinder service) {        // Following the example above for an AIDL interface,        // this gets an instance of the IRemoteInterface, which we can use to call on the service        mIRemoteService = IRemoteService.Stub.asInterface(service);    }    // Called when the connection with the service disconnects unexpectedly    public void onServiceDisconnected(ComponentName className) {        Log.e(TAG, "Service has unexpectedly disconnected");        mIRemoteService = null;    }};

通过IPC传递对象 要实现进程间通信,你的类必须支持Parcelable接口,因为它允许系统分解对象。
要创建一个类支持Parcelable协议,你要做下面这些事:
  1. 让你的类实现Parcelable接口。
  2. 实现writeToParcel,它可以取得对象的当前状态,写入对象到一个Parcel。
  3. 添加CREATOR静态字段到你的类中,他是Parcelable.Creator接口的实现。
  4. 最后,创建一个.aidl文件来声明的parcelable类。
例如,下面的例子是Rect.aidl文件,用来创建一个Rect类:
package android.graphics;// Declare Rect so AIDL can find it and knows that it implements// the parcelable protocol.parcelable Rect;
下面的例子展示了Rect类是怎么实现Parcelable协议的。
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 = newParcelable.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();    }}
警告:不要忘了从其他进程接收数据的安全性。上面的例子中,Rect从Parcel读取4个成员,但是他们的取值范围是由你来判断的。
调用一个IPC函数 下面是调用类调用AIDL定义的远程接口的步骤:
  1. 包含.aidl文件到src/目录中。
  2. 声明一个IBinder接口实例。
  3. 实现ServiceConnection。
  4. 调用Context.bindService(),通过serviceConnection实现。
  5. 在onServiceConnected()实现中,你需要接收IBinder实例,调用YourInterfaceName.Stub.asInterface((IBinder)service)来取得接口类型。
  6. 调用定义在接口中的方法。通常需要抛出DeadObjectException异常,但连接被破坏时抛出,这也是唯一一个由远程方法抛出的异常。
  7. 调用Context.unbindService()解除连接。
在IPC服务器端调用时的一些提醒:
  • 对象的引用被认为是跨线程的。
  • 你可以通过函数参数发送匿名对象。
下面的实例代码演示了怎么调用一个AIDL服务器:
public static class Binding extends Activity {    /** The primary interface we will be calling on the service. */    IRemoteService mService = null;    /** Another interface we use on the service. */    ISecondary mSecondaryService = null;    Button mKillButton;    TextView mCallbackText;    private boolean mIsBound;    /**     * Standard initialization of this activity.  Set up the UI, then wait     * for the user to poke it before doing anything.     */    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.remote_service_binding);        // Watch for button clicks.        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.");    }    /**     * Class for interacting with the main interface of the service.     */    private ServiceConnection mConnection = new ServiceConnection() {        public void onServiceConnected(ComponentName className,                IBinder service) {            // This is called when the connection with the service has been            // established, giving us the service object we can use to            // interact with the service.  We are communicating with our            // service through an IDL interface, so get a client-side            // representation of that from the raw service object.            mService = IRemoteService.Stub.asInterface(service);            mKillButton.setEnabled(true);            mCallbackText.setText("Attached.");            // We want to monitor the service for as long as we are            // connected to it.            try {                mService.registerCallback(mCallback);            } catch (RemoteException e) {                // In this case the service has crashed before we could even                // do anything with it; we can count on soon being                // disconnected (and then reconnected if it can be restarted)                // so there is no need to do anything here.            }            // As part of the sample, tell the user what happened.            Toast.makeText(Binding.this, R.string.remote_service_connected,                    Toast.LENGTH_SHORT).show();        }        public void onServiceDisconnected(ComponentName className) {            // This is called when the connection with the service has been            // unexpectedly disconnected -- that is, its process crashed.            mService = null;            mKillButton.setEnabled(false);            mCallbackText.setText("Disconnected.");            // As part of the sample, tell the user what happened.            Toast.makeText(Binding.this, R.string.remote_service_disconnected,                    Toast.LENGTH_SHORT).show();        }    };    /**     * Class for interacting with the secondary interface of the service.     */    private ServiceConnection mSecondaryConnection = new ServiceConnection() {        public void onServiceConnected(ComponentName className,                IBinder service) {            // Connecting to a secondary interface is the same as any            // other interface.            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) {            // Establish a couple connections with the service, binding            // by interface names.  This allows other applications to be            // installed that replace the remote service by implementing            // the same interface.            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) {                // If we have received the service, and hence registered with                // it, then now is the time to unregister.                if (mService != null) {                    try {                        mService.unregisterCallback(mCallback);                    } catch (RemoteException e) {                        // There is nothing special we need to do if the service                        // has crashed.                    }                }                // Detach our existing connection.                unbindService(mConnection);                unbindService(mSecondaryConnection);                mKillButton.setEnabled(false);                mIsBound = false;                mCallbackText.setText("Unbinding.");            }        }    };    private OnClickListener mKillListener = new OnClickListener() {        public void onClick(View v) {            // To kill the process hosting our service, we need to know its            // PID.  Conveniently our service has a call that will return            // to us that information.            if (mSecondaryService != null) {                try {                    int pid = mSecondaryService.getPid();                    // Note that, though this API allows us to request to                    // kill any process based on its PID, the kernel will                    // still impose standard restrictions on which PIDs you                    // are actually able to kill.  Typically this means only                    // the process running your application and any additional                    // processes created by that app as shown here; packages                    // sharing a common UID will also be able to kill each                    // other's processes.                    Process.killProcess(pid);                    mCallbackText.setText("Killed service process.");                } catch (RemoteException ex) {                    // Recover gracefully from the process hosting the                    // server dying.                    // Just for purposes of the sample, put up a notification.                    Toast.makeText(Binding.this,                            R.string.remote_call_failed,                            Toast.LENGTH_SHORT).show();                }            }        }    };    // ----------------------------------------------------------------------    // Code showing how to deal with callbacks.    // ----------------------------------------------------------------------    /**     * This implementation is used to receive callbacks from the remote     * service.     */    private IRemoteServiceCallback mCallback = new IRemoteServiceCallback.Stub() {        /**         * This is called by the remote service regularly to tell us about         * new values.  Note that IPC calls are dispatched through a thread         * pool running in each process, so the code executing here will         * NOT be running in our main thread like most other things -- so,         * to update the UI, we need to use a Handler to hop over there.         */        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);            }        }    };}



更多相关文章

  1. Android Handler 主线程 子线程 双向通信
  2. Android 之多线程下载原理
  3. Android中打包含有Activity以及资源文件的jar包在工程中调用
  4. Android任务、进程、线程详解
  5. Android P (4)一种绕过Android P上非SDK接口限制的简单方法
  6. Android中使用定制系统的签名文件给应用签名
  7. Android中高效的显示图片之二——在非UI线程中处理图片

随机推荐

  1. Android(安卓)SDCard操作(文件读写,容量
  2. Handle Android(安卓)Out of memory exce
  3. Android设置全屏两种方式
  4. android Camera模块分析
  5. 自动 Android* 应用测试
  6. android source code下载源代码时出错
  7. android图片压缩工具类分享
  8. Android(安卓)使用Arcore 实现多点测距
  9. 来电铃声和通话中的提示音
  10. 每天学习一个Android中的常用框架——0.