Android学习--Service之AIDL
2013-04-07 10:42
363 查看
概述
AIDL:Android Interface Definition Language.通常情况下,在Android中,一个进程是无法访问另一个进程的内存空间的;如果要实现此功能,就需要把对象解码成操作系统能够理解的原始字节,然后才能跨进程传送,AIDL就是用来完成这项工作的。
注意,只有service需要与其他应用进行IPC、并且需要处理多线程任务时,才需要使用AIDL。(如果service不需要进行IPC,可以通过继承Binder实现对外接口;如果需要进行IPC 、但是不需要处理多线程任务,可以使用Messenger实现对外接口。)
定义AIDL接口
AIDL的接口要定义在后缀名为.aidl的文件中,并把该文件保存在持有该service、及打算绑定该service的应用程序的src/文件夹下。在应用程序中创建了.aidl文件后,Android SDK会在此.aidl文件的基础上自动生成一个IBinder接口(此接口的代码存放在工程gen/文件夹下)。在service端,必须在适当的时候实现此IBinder接口;在客户端,可以通过此IBinder与service进行IPC(在客户端不用具体实现此IBinder接口)。创建包含AIDL功能的service,步骤如下:
1、创建.aidl文件:在此文件中定义包含函数签名的编程接口;
2、实现接口:第一步完成后,Android SDK会基于.aidl文件生成一个相应的接口,此接口有一个名字为Stub的抽象内部类(该类继承了Binder并且抽象实现了AIDL接口);必须在service中继承此Stub内部类并实现其内部的函数。
3、将此接口暴露给客户:实现Service并在其onBind()方法中返回Stub的实现。
现将各步骤详细介绍如下:
1、创建.aidl文件
必须用Java语言创建.aidl文件;每个.aidl文件中只能定义一个接口,并且里面只包含接口的声明和方法的签名。
.aidl文件中可以使用任何数据类型(主要用于方法的参数和返回值),甚至其他AIDL生成的接口;但是,AIDL默认支持的只有以下数据类型(对于其他类型必须import引入):
*Java中所有的基本数据类型,及String、ChaSequence;
*List:List里包含的必须是此处列举的数据类型、其他AIDL生成的接口、或声明的Parcelable。可以使用泛类型(如List<String>);即使函数中使用的是List接口,在实体类中实际接收到的通常为ArrayList。
*Map:Map里包含的必须是此处列举的数据类型、其他AIDL生成的接口、或声明的Parcelable。不支持泛型Map;即使函数中使用的是Map接口,在实体类中实际接收到的通常为HashMap。
创建.aidl文件时的注意事项:
*里面的方法可以接收0或多个参数,可以有返回值或返回void;
*所有的非基本类型的参数需要一个定向标签(in、out或inout),指示数据的去向;基本数据类型默认只能是in。(下面示例代码中未见到此标签的使用,不理解其具体作用。)
*.aidl文件中所有的注释都会被包含在生成的IBinder接口中(除了import和package语句前的注释);
*与普通interface不同的是,AIDL中不能包含静态域。
下面一个.aidl文件的示例:
// IRemoteService.aidl package com.example.android; // 在此import非默认支持的数据类型 /** 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); }
把此文件保存在工程的ser/文件夹下,然后SDK工具就会自动在gen/文件夹下生成相应的IBinder接口文件;两个文件的名称相同,后缀不同,前者为.aidl,后者为.java。
2、实现接口
在完成上面一步之后,SDK工具自动生成了一个接口文件,此文件中有一个内部抽象类Stub,它继承了Binder并抽象实现了父类接口;所谓"实现接口"就是要实现此Stub类。
示例代码如下:(使用了匿名机制,实际上包含了实现Stub类、并创建其实例两个过程)
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就是一个Binder实例(因为Stub继承了Binder),是客户端跟service通信的桥梁。
实现AIDL接口的注意事项:
*要考虑多线程的问题,确保service是线程安全的;
*默认情况下,RPC(远程进程调用)是同步的,如果service需要较长时间完成对请求的响应,就不应该在activity的主线程内调用该service;应该在客户端另起一个线程来调用此service,以避免ANR;
*无法向客户端抛异常。
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 } };
}
此时,当客户端调用bindService()绑定此service时,会在客户端的onServiceConnected()方法中得到由onBind()返回的mBinder;在onServiceConnected()方法中要记得调用Stub的asInterface()方法,对得到的IBinder对象进行类型转化。示例代码如下:
IRemoteService mIRemoteService; private ServiceConnection mConnection = new ServiceConnection() { // Called when the connection with the service is established public void onServiceConnected(ComponentName className, IBinder service) { // 将IBinder向下转型为IRemoteService(因为此处的IBinder实际类型为Stub,而Stub实现了IRemoteService接口,所以可以转型成功) 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; } };
当然,客户端必须拥有Stub抽象类的访问权;因此,如果客户端与service不在同应用程序中(通常如此),必须把上面创建的.aidl文件复制到客户端的ser/文件夹下,这样SDK工具会同样在客户端生成AIDL接口,客户端就可以使用Stub的方法了。
通过IPC传递对象
可以在IPC间传递类对象,但是此类需要实现Parcelable接口,并且要确保IPC的另一端拥有此类的源代码。创建支持Parcelable协议的类的步骤如下:
1、让类实现Parcelable接口;
2、实现Parcelable的writeToParcel()方法,此方法用于把当前类写进Parcel;
3、添加一个实现了Parcelable.Creator接口、名称为CREATOR的域;
4、创建一个.aidl文件,在其中声明此类是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 = 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(); } }
下面是Rect.aidl文件,声明Rect类是parcelable的:
package android.graphics; // Declare Rect so AIDL can find it and knows that it implements // the parcelable protocol. parcelable Rect;//注意此处的parcelable为小写
调用IPC另一端的方法
要调用AIDL中定义的远程接口中的方法,客户端需要完成以下几步:1、在ser/文件夹下包含相应的.aidl文件,系统会基于此文件生成包含IBinder接口的文件;
2、声明上述IBinder接口类型的成员变量;(不用初始化,赋值操作在下述的onServiceConnected()中完成)
3、实现ServiceConnection;
4、调用Context.bindService(),并把ServiceConnection的实例传递给这个函数;
5、之后会在ServiceConnection的onServiceConnected()方法中得到一个IBinder对象,要记得调用AIDL接口中的asInterface()方法对其进行类型转化。
6、接下来就可以通过得到的IBinder对象调用远程接口中的方法了,但是此时一定要记得捕获DeadObjectException(此异常会在连接意外中断时抛出,是由远程方法抛出的唯一异常);
7、要解除绑定,调用Context.unbindService()。
还有以下两点需注意:
*Objects are reference counted across processes.
*可以向函数传递匿名对象。
示例代码如下:
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); } } }; }
此部分的所有示例代码均节选自官方的APIDemos中的Remote Service示例。
相关文章推荐
- Android Service学习之AIDL, Parcelable和远程服务
- Android Service学习之AIDL, Parcelable和远程服务
- Android Service学习之AIDL, Parcelable和远程服务
- Android Service学习之AIDL实例
- Android Service AIDL的学习,传递对象
- android学习之remote service 的aidl详解
- Android Service学习之AIDL, Parcelable和远程服务
- Android Service学习之AIDL, Parcelable和远程服务
- Android Service学习之AIDL, Parcelable和远程服务
- Android Service学习之AIDL, Parcelable和远程服务
- Android Service学习之AIDL, Parcelable和远程服务
- Android Service学习之AIDL, Parcelable和远程服务
- Android Service学习之AIDL实例
- Android Service学习之AIDL, Parcelable和远程服务
- android服务学习service之AIDL
- Android Service学习之AIDL, Parcelable和远程服务
- 一个简单的demo学习Android远程Service(AIDL的使用
- Android Service学习之AIDL, Parcelable和远程服务
- Android Service学习之AIDL, Parcelable和远程服务
- Android Service学习之AIDL, Parcelable和远程服务