Android 使用AIDL实现进程间的通信
在Android中,如果我們需要在不同進程間實現(xiàn)通信,就需要用到AIDL技術(shù)去完成。
AIDL(android?Interface Definition Language)是一種接口定義語言,編譯器通過*.aidl文件的描述信息生成符合通信協(xié)議的Java代碼,我們無需自己去寫這段繁雜的代碼,只需要在需要的時候調(diào)用即可,通過這種方式我們就可以完成進程間的通信工作。關(guān)于AIDL的編寫規(guī)則我在這里就不多介紹了,讀者可以到網(wǎng)上查找一下相關(guān)資料。
接下來,我就演示一個操作AIDL的最基本的流程。
首先,我們需要建立一個服務(wù)端的工程,如圖所以:
?
在IPerson.aidl中我們定義了一個“問候”的方法,代碼如下:
package com.scott.aidl; interface IPerson {String greet(String someone); }在Eclipse插件的幫助下,編譯器會自動在gen目錄中生成對應(yīng)的IPerson.java文件,格式化后的代碼如下:
package com.scott.aidl;public interface IPerson extends android.os.IInterface {/** Local-side IPC implementation stub class. */public static abstract class Stub extends android.os.Binder implements com.scott.aidl.IPerson {private static final java.lang.String DESCRIPTOR = "com.scott.aidl.IPerson";/** Construct the stub at attach it to the interface. */public Stub() {this.attachInterface(this, DESCRIPTOR);}/*** Cast an IBinder object into an com.scott.aidl.IPerson interface,* generating a proxy if needed.*/public static com.scott.aidl.IPerson asInterface(android.os.IBinder obj) {if ((obj == null)) {return null;}android.os.IInterface iin = (android.os.IInterface) obj.queryLocalInterface(DESCRIPTOR);if (((iin != null) && (iin instanceof com.scott.aidl.IPerson))) {return ((com.scott.aidl.IPerson) iin);}return new com.scott.aidl.IPerson.Stub.Proxy(obj);}public android.os.IBinder asBinder() {return this;}@Overridepublic boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags)throws android.os.RemoteException {switch (code) {case INTERFACE_TRANSACTION: {reply.writeString(DESCRIPTOR);return true;}case TRANSACTION_greet: {data.enforceInterface(DESCRIPTOR);java.lang.String _arg0;_arg0 = data.readString();java.lang.String _result = this.greet(_arg0);reply.writeNoException();reply.writeString(_result);return true;}}return super.onTransact(code, data, reply, flags);}private static class Proxy implements com.scott.aidl.IPerson {private android.os.IBinder mRemote;Proxy(android.os.IBinder remote) {mRemote = remote;}public android.os.IBinder asBinder() {return mRemote;}public java.lang.String getInterfaceDescriptor() {return DESCRIPTOR;}public java.lang.String greet(java.lang.String someone) throws android.os.RemoteException {android.os.Parcel _data = android.os.Parcel.obtain();android.os.Parcel _reply = android.os.Parcel.obtain();java.lang.String _result;try {_data.writeInterfaceToken(DESCRIPTOR);_data.writeString(someone);mRemote.transact(Stub.TRANSACTION_greet, _data, _reply, 0);_reply.readException();_result = _reply.readString();} finally {_reply.recycle();_data.recycle();}return _result;}}static final int TRANSACTION_greet = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);}public java.lang.String greet(java.lang.String someone) throws android.os.RemoteException; }該文件的大綱視圖如下:
IPerson接口中的抽象內(nèi)部類Stub繼承android.os.Binder類并實現(xiàn)IPerson接口,比較重要的方法是asInterface(IBinder)方法,該方法會將IBinder類型的對象轉(zhuǎn)換成IPerson類型,必要的時候生成一個代理對象返回結(jié)果。
接下來就是我們的Service了:
package com.scott.server;import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.RemoteException; import android.util.Log;import com.scott.aidl.IPerson;public class AIDLService extends Service {private static final String TAG = "AIDLService";IPerson.Stub stub = new IPerson.Stub() {@Overridepublic String greet(String someone) throws RemoteException {Log.i(TAG, "greet() called");return "hello, " + someone;}};@Overridepublic IBinder onBind(Intent intent) {Log.i(TAG, "onBind() called");return stub;}@Overridepublic boolean onUnbind(Intent intent) {Log.i(TAG, "onUnbind() called");return true;}@Overridepublic void onDestroy() {super.onDestroy();Log.i(TAG, "onDestroy() called");} }我們實現(xiàn)了IPerson.Stub這個抽象類的greet方法,然后再onBind(Intent)方法中返回我們的stub實例,這樣一來調(diào)用方獲取的IPerson.Stub就是我們的這個實例,greet方法也會按照我們的期望那樣執(zhí)行。
當然,要想讓Service生效,我們還需要在AndroidManifest.xml中做一些配置工作:
<service android:name=".AIDLService"><intent-filter><action android:name="android.intent.action.AIDLService" /><category android:name="android.intent.category.DEFAULT" /></intent-filter> </service>服務(wù)端已經(jīng)完成了,接下來我們就該完成客戶端的工作了。我已經(jīng)建好了一個客戶端工程,如圖:
我們只需要把IPerson.aidl文件拷到相應(yīng)的目錄中即可,編譯器同樣會生成相對應(yīng)的IPerson.java文件,這一部分和服務(wù)端沒什么區(qū)別。這樣一來,服務(wù)端和客戶端就在通信協(xié)議上達到了統(tǒng)一。我們主要工作在MainActivity中完成。
MainActivity代碼如下:
package com.scott.client;import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast;import com.scott.aidl.IPerson;public class MainActivity extends Activity {private Button bindBtn;private Button greetBtn;private Button unbindBtn;private IPerson person;private ServiceConnection conn = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {Log.i("ServiceConnection", "onServiceConnected() called");person = IPerson.Stub.asInterface(service);}@Overridepublic void onServiceDisconnected(ComponentName name) {//This is called when the connection with the service has been unexpectedly disconnected,//that is, its process crashed. Because it is running in our same process, we should never see this happen.Log.i("ServiceConnection", "onServiceDisconnected() called");}};@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);bindBtn = (Button) findViewById(R.id.bindBtn);bindBtn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Intent intent = new Intent("android.intent.action.AIDLService");bindService(intent, conn, Context.BIND_AUTO_CREATE);bindBtn.setEnabled(false);greetBtn.setEnabled(true);unbindBtn.setEnabled(true);}});greetBtn = (Button) findViewById(R.id.greetBtn);greetBtn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {try {String retVal = person.greet("scott");Toast.makeText(MainActivity.this, retVal, Toast.LENGTH_SHORT).show();} catch (RemoteException e) {Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();}}});unbindBtn = (Button) findViewById(R.id.unbindBtn);unbindBtn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {unbindService(conn);bindBtn.setEnabled(true);greetBtn.setEnabled(false);unbindBtn.setEnabled(false);}});} }從代碼中可以看到,我們要重寫ServiceConnection中的onServiceConnected方法將IBinder類型的對像轉(zhuǎn)換成我們的IPerson類型。到現(xiàn)在我們就剩下最后一個步驟了,這個環(huán)節(jié)也是最為關(guān)鍵的,就是綁定我們需要的服務(wù)。我們通過服務(wù)端Service定義的“android.intent.action.AIDLService”這個標識符來綁定其服務(wù),這樣客戶端和服務(wù)端就實現(xiàn)了通信的連接,我們就可以調(diào)用IPerson中的“問候”方法了。
最后,貼幾張客戶端演示過程圖。
?
?
?
?按照順序分別是:初始界面;點擊bindService后界面;點擊greet后界面;點擊unbindService后界面。
操作過程中的日志如下:
轉(zhuǎn)載于:https://www.cnblogs.com/zhujiabin/p/7093288.html
總結(jié)
以上是生活随笔為你收集整理的Android 使用AIDL实现进程间的通信的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 贝塞尔曲线与CSS3动画、SVG和can
- 下一篇: js学习总结----获取数组最大值