編輯:關於 Android 程式設計
IPC 是什麼大概不用多介紹。Android 系統中各進程之間無法共享內存,那麼兩個不同應用之間需要通訊該怎麼辦?
舉個真實場景:公司有一個項目要更新,產品希望在現有項目基礎上開發一個插件,但這個插件功能和界面都比較複雜,塞不進原項目進程;同時它又要用到原項目裡已經寫好的一些能力。兩個進程不共享內存,問題就來了。這時候需要一套跨進程數據通信機制,也就是 AIDL。
假設現有項目已經封裝好一個成熟的計算類,新開發的應用想直接復用,不想重寫一遍,那就可以通過 AIDL 來實現。把提供服務的一方稱為 AIDLCalculateDemoServer(服務端),調用方稱為 AIDLCalculateDemoClient(客戶端),典型的客戶端/服務器模式。先看看工程結構:

圖1-1 服務器 圖1-2 客戶端
現在的目標是:客戶端輸入 num1 和 num2,通過遠程調用服務端接口完成運算,服務端把結果返回給客戶端顯示。效果圖如下:

第一步是定義 AIDL 接口。客戶端和服務端都要定義,且必須處於同一個包名下,也就是圖 1-1、圖 1-2 中的 com.example.aidl.calculate.CalculateInterface:
package com.example.aidl.calculate; interface CalculateInterface { double doCalculate(double a, double b); }
編譯之後,gen/com.example.aidl.calculate 目錄下會自動生成 CalculateInterface.java,裡面包含了 Stub 與 Proxy 兩個內部類,前者供服務端繼承,後者供客戶端調用,序列化與跨進程傳輸的細節都由它隱式完成。
接口定義好之後,看服務端。核心是 CalculateService,它繼承 Service,並在裡面為 AIDL 接口賦予真實含義:
package com.example.calculate; import com.example.aidl.calculate.CalculateInterface; import com.example.aidl.calculate.CalculateInterface.Stub; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; public class CalculateService extends Service { private static final String TAG = "CalculateService"; @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub logE("onBind()"); return mBinder; } @Override public void onCreate() { // TODO Auto-generated method stub logE("onCreate()"); super.onCreate(); } @Override public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub logE("onStart()"); super.onStart(intent, startId); } @Override public boolean onUnbind(Intent intent) { // TODO Auto-generated method stub logE("onUnbind()"); return super.onUnbind(intent); } @Override public void onDestroy() { // TODO Auto-generated method stub logE("onDestroy()"); super.onDestroy(); } private static void logE(String str) { Log.e(TAG, "--------" + str + "--------"); } private final CalculateInterface.Stub mBinder = new CalculateInterface.Stub() { @Override public double doCalculate(double a, double b) throws RemoteException { // TODO Auto-generated method stub Log.e("Calculate", "遠程計算中"); Calculate calculate = new Calculate(); double answer = calculate.calculateSum(a, b); return answer; } }; }
關鍵點在 onBind 返回了 Stub 對象,客戶端綁定成功後拿到的就是這個 Binder。
客戶端則需要綁定服務,並通過 ServiceConnection 接收 Binder:
package com.example.calculate; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.graphics.Color; 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.EditText; import android.widget.TextView; import com.example.aidl.calculate.CalculateInterface; import com.example.aidlcaculatedemoclient.R; public class CalculateClient extends Activity { private static final String TAG = "CalculateClient"; private Button btnCalculate; private EditText etNum1; private EditText etNum2; private TextView tvResult; private CalculateInterface mService; private ServiceConnection mServiceConnection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { // TODO Auto-generated method stub logE("disconnect service"); mService = null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { // TODO Auto-generated method stub logE("connect service"); mService = CalculateInterface.Stub.asInterface(service); } }; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.main); Bundle args = new Bundle(); Intent intent = new Intent("com.example.calculate.CalculateService"); intent.putExtras(args); bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE); etNum1 = (EditText) findViewById(R.id.et_num_one); etNum2 = (EditText) findViewById(R.id.et_num_two); tvResult = (TextView) findViewById(R.id.tv_result); btnCalculate = (Button) findViewById(R.id.btn_cal); btnCalculate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub logE("開始遠程運算"); try { double num1 = Double.parseDouble(etNum1.getText().toString()); double num2 = Double.parseDouble(etNum2.getText().toString()); String answer = "計算結果:" + mService.doCalculate(num1, num2); tvResult.setTextColor(Color.BLUE); tvResult.setText(answer); } catch (RemoteException e) { } } }); } private void logE(String str) { Log.e(TAG, "--------" + str + "--------"); } }
onServiceConnected 裡的 CalculateInterface.Stub.asInterface(service) 是整個流程的樞紐:如果服務與客戶端在同一進程,返回的就是本地 Stub 實現;如果在不同進程,返回的是 Proxy,方法調用會被轉成 Parcel 數據跨進程發送。
最後是服務端的配置文件:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.aidlcaculatedemoserver" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.aidlcaculatedemoserver.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name="com.example.calculate.CalculateService"> <intent-filter> <action android:name="com.example.calculate.CalculateService" /> </intent-filter> </service> </application> </manifest>
1. 客戶端與服務端的 AIDL 接口文件所在的包名必須完全一致,否則生成的 Stub 類對不上。
2. 必須有一個 Service 類配合,AIDL 本身不能獨立存在。
3. 服務端要在 AndroidManifest 中註冊 Service,並用 intent-filter 顯式聲明 action,客戶端才能通過隱式 Intent 綁定成功。
4. AIDL 支持的基本數據類型有限(byte、boolean、char、int、long、float、double、String、CharSequence 及 List、Map),自定義對象必須實現 Parcelable 並提前聲明,否則會拋 ClassNotFoundException。
Android 實現自定義華麗水波紋效果
先來看看效果 實現效果 模擬水波紋的效果:點擊螢幕就有圓環出現,半徑從小到大、透明度從大到小(0 為透明)。 實現思路 1. 自定義類繼承 View。 2. 定義每個圓
ListView + GridView 實作仿朋友圈動態流,徹底告別焦點衝突
專案裡有一塊需要做成像微信朋友圈那樣的動態流。最初想用 RecyclerView 嵌套 RecyclerView,介面其餘部分都完成了,唯獨圖片九宮格那塊始終調不出來,也
CheckBox 復選框控件的動態添加與取值
本文介紹 CheckBox 復選框控件的使用方法,重點示範如何用 Java 代碼動態地添加復選框並取得勾選結果。 一、簡介 類結構圖: 二、使用方法 這裡示範用 Ja
Android 左右聲道控制:AudioTrack 的立體聲平衡實踐
效果預覽 實現思路 核心用的是 AudioTrack。手機通常只有左右兩個聲道,播放時既可以選擇單聲道,也可以選擇雙聲道(立體聲)。 翻一遍 AudioTrack 的