使用AIDL設(shè)計(jì)遠(yuǎn)程接口(Designing a Remote Interface Using AIDL)
由于每個(gè)應(yīng)用程序都運(yùn)行在自己的進(jìn)程空間,并且可以從應(yīng)用程序UI運(yùn)行另一個(gè)服務(wù)進(jìn)程,而且經(jīng)常會(huì)在不同的進(jìn)程間傳遞對(duì)象。在Android平臺(tái),一個(gè)進(jìn)程通常不能訪問(wèn)另一個(gè)進(jìn)程的內(nèi)存空間,所以要想對(duì)話,需要將對(duì)象分解成操作系統(tǒng)可以理解的基本單元,并且有序的通過(guò)進(jìn)程邊界。
通過(guò)代碼來(lái)實(shí)現(xiàn)這個(gè)數(shù)據(jù)傳輸過(guò)程是冗長(zhǎng)乏味的,Android提供了AIDL工具來(lái)處理這項(xiàng)工作。
AIDL (Android Interface Definition Language)是一種IDL 語(yǔ)言,用于生成可以在Android設(shè)備上兩個(gè)進(jìn)程之間進(jìn)行進(jìn)程間通信(IPC)的代碼。如果在一個(gè)進(jìn)程中(例如Activity)要調(diào)用另一個(gè)進(jìn)程中(例如Service)對(duì)象的操作,就可以使用AIDL生成可序列化的參數(shù)。
AIDL IPC機(jī)制是面向接口的,像COM或Corba一樣,但是更加輕量級(jí)。它是使用代理類(lèi)在客戶端和實(shí)現(xiàn)端傳遞數(shù)據(jù)。
使用AIDL實(shí)現(xiàn)IPC(Implementing IPC Using AIDL)
使用AIDL實(shí)現(xiàn)IPC服務(wù)的步驟是:
1. 創(chuàng)建.aidl文件-該文件(YourInterface.aidl)定義了客戶端可用的方法和數(shù)據(jù)的接口。
2. 在makefile文件中加入.aidl文件-(Eclipse中的ADT插件提供管理功能)Android包括名為AIDL的編譯器,位于tools/文件夾。
3. 實(shí)現(xiàn)接口-AIDL編譯器從AIDL接口文件中利用Java語(yǔ)言創(chuàng)建接口,該接口有一個(gè)繼承的命名為Stub的內(nèi)部抽象類(lèi)(并且實(shí)現(xiàn)了一些IPC調(diào)用的附加方法),要做的就是創(chuàng)建一個(gè)繼承于YourInterface.Stub的類(lèi)并且實(shí)現(xiàn)在.aidl文件中聲明的方法。
4. 向客戶端公開(kāi)接口-如果是編寫(xiě)服務(wù),應(yīng)該繼承Service并且重載Service.onBind(Intent) 以返回實(shí)現(xiàn)了接口的對(duì)象實(shí)例
創(chuàng)建.aidl文件(Create an .aidl File)
AIDL使用簡(jiǎn)單的語(yǔ)法來(lái)聲明接口,描述其方法以及方法的參數(shù)和返回值。這些參數(shù)和返回值可以是任何類(lèi)型,甚至是其他AIDL生成的接口。重要的是必須導(dǎo)入所有非內(nèi)置類(lèi)型,哪怕是這些類(lèi)型是在與接口相同的包中。下面是AIDL能支持的數(shù)據(jù)類(lèi)型:
l Java編程語(yǔ)言的主要類(lèi)型 (int, boolean等) — 不需要 import 語(yǔ)句。
l 以下的類(lèi) (不需要import 語(yǔ)句):
n String
n List -列表中的所有元素必須是在此列出的類(lèi)型,包括其他AIDL生成的接口和可打包類(lèi)型。List可以像一般的類(lèi)(例如List<String>)那樣使用,另一邊接收的具體類(lèi)一般是一個(gè)ArrayList,這些方法會(huì)使用List接口。
n Map - Map中的所有元素必須是在此列出的類(lèi)型,包括其他AIDL生成的接口和可打包類(lèi)型。一般的maps(例如Map<String,Integer>)不被支持,另一邊接收的具體類(lèi)一般是一個(gè)HashMap,這些方法會(huì)使用Map接口。
n CharSequence -該類(lèi)是被TextView和其他控件對(duì)象使用的字符序列。
l 通常引引用方式傳遞的其他AIDL生成的接口,必須要import 語(yǔ)句聲明
l 實(shí)現(xiàn)了Parcelable protocol 以及按值傳遞的自定義類(lèi),必須要import 語(yǔ)句聲明。
實(shí)現(xiàn)接口(Implementing the Interface)
AIDL生成了與.aidl文件同名的接口,如果使用Eclipse插件,AIDL會(huì)做為編譯過(guò)程的一部分自動(dòng)運(yùn)行(不需要先運(yùn)行AIDL再編譯項(xiàng)目),如果沒(méi)有插件,就要先運(yùn)行AIDL。
生成的接口包含一個(gè)名為Stub的抽象的內(nèi)部類(lèi),該類(lèi)聲明了所有.aidl中描述的方法,Stub還定義了少量的輔助方法,尤其是asInterface(),通過(guò)它或以獲得IBinder(當(dāng)applicationContext.bindService()成功調(diào)用時(shí)傳遞到客戶端的onServiceConnected())并且返回用于調(diào)用IPC方法的接口實(shí)例
要實(shí)現(xiàn)自己的接口,就從YourInterface.Stub類(lèi)繼承,然后實(shí)現(xiàn)相關(guān)的方法(可以創(chuàng)建.aidl文件然后實(shí)現(xiàn)stub方法而不用在中間編譯,Android編譯過(guò)程會(huì)在.java文件之前處理.aidl文件)。
這個(gè)例子實(shí)現(xiàn)了對(duì)IRemoteService接口的調(diào)用,這里使用了匿名對(duì)象并且只有一個(gè)getPid()接口。
這里是實(shí)現(xiàn)接口的幾條說(shuō)明:
l 不會(huì)有返回給調(diào)用方的異常
l 默認(rèn)IPC調(diào)用是同步的。如果已知IPC服務(wù)端會(huì)花費(fèi)很多毫秒才能完成,那就不要在Activity或View線程中調(diào)用,否則會(huì)引起應(yīng)用程序掛起(Android可能會(huì)顯示“應(yīng)用程序未響應(yīng)”對(duì)話框),可以試著在獨(dú)立的線程中調(diào)用。
l AIDL接口中只支持方法,不能聲明靜態(tài)成員。
向客戶端暴露接口(Exposing Your Interface to Clients)
在完成了接口的實(shí)現(xiàn)后需要向客戶端暴露接口了,也就是發(fā)布服務(wù),實(shí)現(xiàn)的方法是繼承 Service,然后實(shí)現(xiàn)以Service.onBind(Intent)返回一個(gè)實(shí)現(xiàn)了接口的類(lèi)對(duì)象。下面的代碼片斷表示了暴露IRemoteService接口給客戶端的方式。
public class RemoteService extends Service { ... @Override public IBinder onBind(Intent intent) { // Select the interface to return. If your service only implements // a single interface, you can just return it here without checking // the Intent. if (IRemoteService.class.getName().equals(intent.getAction())) { return mBinder; } if (ISecondary.class.getName().equals(intent.getAction())) { return mSecondaryBinder; } return null; } /** * The IRemoteInterface is defined through IDL */ private final IRemoteService.Stub mBinder = new IRemoteService.Stub() { public void registerCallback(IRemoteServiceCallback cb) { if (cb != null) mCallbacks.register(cb); } public void unregisterCallback(IRemoteServiceCallback cb) { if (cb != null) mCallbacks.unregister(cb); } }; /** * A secondary interface to the service. */ private final ISecondary.Stub mSecondaryBinder = new ISecondary.Stub() { public int getPid() { return Process.myPid(); } public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) { } }; }
使用可打包接口傳遞參數(shù)Pass by value Parameters using Parcelables
如果有類(lèi)想要能過(guò)AIDL在進(jìn)程之間傳遞,這一想法是可以實(shí)現(xiàn)的,必須確保這個(gè)類(lèi)在IPC的兩端的有效性,通常的情形是與一個(gè)啟動(dòng)的服務(wù)通信。
這里列出了使類(lèi)能夠支持Parcelable的4個(gè)步驟:【譯者注:原文為5,但列表為4項(xiàng),疑為作者筆誤】
1. 使該類(lèi)實(shí)現(xiàn)Parcelabel接口。
2. 實(shí)現(xiàn)public void writeToParcel(Parcel out) 方法,以便可以將對(duì)象的當(dāng)前狀態(tài)寫(xiě)入包裝對(duì)象中。
3. 增加名為CREATOR的構(gòu)造器到類(lèi)中,并實(shí)現(xiàn)Parcelable.Creator接口。
4. 最后,但同樣重要的是,創(chuàng)建AIDL文件聲明這個(gè)可打包的類(lèi)(見(jiàn)下文),如果使用的是自定義的編譯過(guò)程,那么不要編譯此AIDL文件,它像C語(yǔ)言的頭文件一樣不需要編譯。
AIDL會(huì)使用這些方法的成員序列化和反序列化對(duì)象。
這個(gè)例子演示了如何讓Rect類(lèi)實(shí)現(xiàn)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(); } }
這個(gè)是Rect.aidl文件。
序列化Rect類(lèi)的工作相當(dāng)簡(jiǎn)單,對(duì)可打包的其他類(lèi)型的數(shù)據(jù)可以參見(jiàn)Parcel類(lèi)。
調(diào)用IPC方法(Calling an IPC Method)
這里給出了調(diào)用遠(yuǎn)端接口的步驟:
1. 聲明.aidl文件中定義的接口類(lèi)型的變量。
2. 實(shí)現(xiàn)ServiceConnection
3. 調(diào)用Context.bindService(),傳遞ServiceConnection的實(shí)現(xiàn)
4. 在ServiceConnection.onServiceConnected()方法中會(huì)接收到IBinder對(duì)象,調(diào)用YourInterfaceName.Stub.asInterface((IBinder)service)將返回值轉(zhuǎn)換為YourInterface類(lèi)型
5. 調(diào)用接口中定義的方法。應(yīng)該總是捕獲連接被打斷時(shí)拋出的DeadObjectException異常,這是遠(yuǎn)端方法唯一的異常。
6. 調(diào)用Context.unbindService()斷開(kāi)連接
這里是幾個(gè)調(diào)用IPC服務(wù)的提示:
l 對(duì)象是在進(jìn)程間進(jìn)行引用計(jì)數(shù)
l 可以發(fā)送匿名對(duì)象作為方法參數(shù)
以下是演示調(diào)用AIDL創(chuàng)建的服務(wù),可以在ApiDemos項(xiàng)目中獲取遠(yuǎn)程服務(wù)的示例。
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); } } }; }
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
