閱讀998 返回首頁    go 阿裏雲 go 技術社區[雲棲]


android跨進程通信(IPC):使用AIDL

AIDL的作用

AIDL (Android Interface Definition Language) 是一種IDL 語言,用於生成可以在Android設備上兩個進程之間進行進程間通信(interprocess communication, IPC)的代碼。如果在一個進程中(例如Activity)要調用另一個進程中(例如Service)對象的操作,就可以使用AIDL生成可序列化的參數。
AIDL IPC機製是麵向接口的,像COM或Corba一樣,但是更加輕量級。它是使用代理類在客戶端和實現端傳遞數據。

選擇AIDL的使用場合

官方文檔特別提醒我們何時使用AIDL是必要的:隻有你允許客戶端從不同的應用程序為了進程間的通信而去訪問你的service,以及想在你的service處理多線程。如果不需要進行不同應用程序間的並發通信(IPC),you should create your interface by implementing a Binder;或者你想進行IPC,但不需要處理多線程的,則implement your interface using a Messenger。無論如何,在使用AIDL前,必須要理解如何綁定service——bindService。如何綁定服務,請參考我的另一篇文章:https://blog.csdn.net/singwhatiwanna/article/details/9058143。這裏先假設你已經了解如何使用bindService。

如何使用AIDL

1.先建立一個android工程,用作服務端

創建一個android工程,用來充當跨進程通信的服務端。

2.創建一個包名用來存放aidl文件

創建一個包名用來存放aidl文件,比如com.ryg.sayhi.aidl,在裏麵新建IMyService.aidl文件,如果需要訪問自定義對象,還需要建立對象的aidl文件,這裏我們由於使用了自定義對象Student,所以,還需要創建Student.aidl和Student.java。注意,這三個文件,需要都放在com.ryg.sayhi.aidl包裏。下麵描述如何寫這三個文件。

IMyService.aidl代碼如下:
[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. package com.ryg.sayhi.aidl;  
  2.   
  3. import com.ryg.sayhi.aidl.Student;  
  4.   
  5. interface IMyService {  
  6.   
  7.     List<Student> getStudent();  
  8.     void addStudent(in Student student);  
  9. }  
說明:
aidl中支持的參數類型為:基本類型(int,long,char,boolean等),String,CharSequence,List,Map,其他類型必須使用import導入,即使它們可能在同一個包裏,比如上麵的Student,盡管它和IMyService在同一個包中,但是還是需要顯示的import進來。
另外,接口中的參數除了aidl支持的類型,其他類型必須標識其方向:到底是輸入還是輸出抑或兩者兼之,用in,out或者inout來表示,上麵的代碼我們用in標記,因為它是輸入型參數。
在gen下麵可以看到,eclipse為我們自動生成了一個代理類
public static abstract class Stub extends android.os.Binder implements com.ryg.sayhi.aidl.IMyService
可見這個Stub類就是一個普通的Binder,隻不過它實現了我們定義的aidl接口。它還有一個靜態方法
public static com.ryg.sayhi.aidl.IMyService asInterface(android.os.IBinder obj)
這個方法很有用,通過它,我們就可以在客戶端中得到IMyService的實例,進而通過實例來調用其方法。

Student.aidl代碼如下:
[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. package com.ryg.sayhi.aidl;  
  2.   
  3. parcelable Student;  
說明:這裏parcelable是個類型,首字母是小寫的,和Parcelable接口不是一個東西,要注意。

Student.java代碼如下:
[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. package com.ryg.sayhi.aidl;  
  2.   
  3. import java.util.Locale;  
  4.   
  5. import android.os.Parcel;  
  6. import android.os.Parcelable;  
  7.   
  8. public final class Student implements Parcelable {  
  9.   
  10.     public static final int SEX_MALE = 1;  
  11.     public static final int SEX_FEMALE = 2;  
  12.   
  13.     public int sno;  
  14.     public String name;  
  15.     public int sex;  
  16.     public int age;  
  17.   
  18.     public Student() {  
  19.     }  
  20.   
  21.     public static final Parcelable.Creator<Student> CREATOR = new  
  22.             Parcelable.Creator<Student>() {  
  23.   
  24.                 public Student createFromParcel(Parcel in) {  
  25.                     return new Student(in);  
  26.                 }  
  27.   
  28.                 public Student[] newArray(int size) {  
  29.                     return new Student[size];  
  30.                 }  
  31.   
  32.             };  
  33.   
  34.     private Student(Parcel in) {  
  35.         readFromParcel(in);  
  36.     }  
  37.   
  38.     @Override  
  39.     public int describeContents() {  
  40.         return 0;  
  41.     }  
  42.   
  43.     @Override  
  44.     public void writeToParcel(Parcel dest, int flags) {  
  45.         dest.writeInt(sno);  
  46.         dest.writeString(name);  
  47.         dest.writeInt(sex);  
  48.         dest.writeInt(age);  
  49.     }  
  50.   
  51.     public void readFromParcel(Parcel in) {  
  52.         sno = in.readInt();  
  53.         name = in.readString();  
  54.         sex = in.readInt();  
  55.         age = in.readInt();  
  56.     }  
  57.       
  58.     @Override  
  59.     public String toString() {  
  60.         return String.format(Locale.ENGLISH, "Student[ %d, %s, %d, %d ]", sno, name, sex, age);  
  61.     }  
  62.   
  63. }  
說明:通過AIDL傳輸非基本類型的對象,被傳輸的對象需要序列化,序列化功能java有提供,但是android sdk提供了更輕量級更方便的方法,即實現Parcelable接口,關於android的序列化,我會在以後寫文章介紹。這裏隻要簡單理解一下就行,大意是要實現如下函數
readFromParcel : 從parcel中讀取對象
writeToParcel :將對象寫入parcel
describeContents:返回0即可
Parcelable.Creator<Student> CREATOR:這個照著上麵的代碼抄就可以
需要注意的是,readFromParcel和writeToParcel操作數據成員的順序要一致

3.創建服務端service

創建一個service,比如名為MyService.java,代碼如下:
[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. /** 
  2.  * @author scott 
  3.  */  
  4. public class MyService extends Service  
  5. {  
  6.     private final static String TAG = "MyService";  
  7.     private static final String PACKAGE_SAYHI = "com.example.test";  
  8.   
  9.     private NotificationManager mNotificationManager;  
  10.     private boolean mCanRun = true;  
  11.     private List<Student> mStudents = new ArrayList<Student>();  
  12.       
  13.     //這裏實現了aidl中的抽象函數  
  14.     private final IMyService.Stub mBinder = new IMyService.Stub() {  
  15.   
  16.         @Override  
  17.         public List<Student> getStudent() throws RemoteException {  
  18.             synchronized (mStudents) {  
  19.                 return mStudents;  
  20.             }  
  21.         }  
  22.   
  23.         @Override  
  24.         public void addStudent(Student student) throws RemoteException {  
  25.             synchronized (mStudents) {  
  26.                 if (!mStudents.contains(student)) {  
  27.                     mStudents.add(student);  
  28.                 }  
  29.             }  
  30.         }  
  31.   
  32.         //在這裏可以做權限認證,return false意味著客戶端的調用就會失敗,比如下麵,隻允許包名為com.example.test的客戶端通過,  
  33.         //其他apk將無法完成調用過程  
  34.         public boolean onTransact(int code, Parcel data, Parcel reply, int flags)  
  35.                 throws RemoteException {  
  36.             String packageName = null;  
  37.             String[] packages = MyService.this.getPackageManager().  
  38.                     getPackagesForUid(getCallingUid());  
  39.             if (packages != null && packages.length > 0) {  
  40.                 packageName = packages[0];  
  41.             }  
  42.             Log.d(TAG, "onTransact: " + packageName);  
  43.             if (!PACKAGE_SAYHI.equals(packageName)) {  
  44.                 return false;  
  45.             }  
  46.   
  47.             return super.onTransact(code, data, reply, flags);  
  48.         }  
  49.   
  50.     };  
  51.   
  52.     @Override  
  53.     public void onCreate()  
  54.     {  
  55.         Thread thr = new Thread(nullnew ServiceWorker(), "BackgroundService");  
  56.         thr.start();  
  57.   
  58.         synchronized (mStudents) {  
  59.             for (int i = 1; i < 6; i++) {  
  60.                 Student student = new Student();  
  61.                 student.name = "student#" + i;  
  62.                 student.age = i * 5;  
  63.                 mStudents.add(student);  
  64.             }  
  65.         }  
  66.   
  67.         mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  
  68.         super.onCreate();  
  69.     }  
  70.   
  71.     @Override  
  72.     public IBinder onBind(Intent intent)  
  73.     {  
  74.         Log.d(TAG, String.format("on bind,intent = %s", intent.toString()));  
  75.         displayNotificationMessage("服務已啟動");  
  76.         return mBinder;  
  77.     }  
  78.   
  79.     @Override  
  80.     public int onStartCommand(Intent intent, int flags, int startId)  
  81.     {  
  82.         return super.onStartCommand(intent, flags, startId);  
  83.     }  
  84.   
  85.     @Override  
  86.     public void onDestroy()  
  87.     {  
  88.         mCanRun = false;  
  89.         super.onDestroy();  
  90.     }  
  91.   
  92.     private void displayNotificationMessage(String message)  
  93.     {  
  94.         Notification notification = new Notification(R.drawable.icon, message,  
  95.                 System.currentTimeMillis());  
  96.         notification.flags = Notification.FLAG_AUTO_CANCEL;  
  97.         notification.defaults |= Notification.DEFAULT_ALL;  
  98.         PendingIntent contentIntent = PendingIntent.getActivity(this0,  
  99.                 new Intent(this, MyActivity.class), 0);  
  100.         notification.setLatestEventInfo(this"我的通知", message,  
  101.                 contentIntent);  
  102.         mNotificationManager.notify(R.id.app_notification_id + 1, notification);  
  103.     }  
  104.   
  105.     class ServiceWorker implements Runnable  
  106.     {  
  107.         long counter = 0;  
  108.   
  109.         @Override  
  110.         public void run()  
  111.         {  
  112.             // do background processing here.....  
  113.             while (mCanRun)  
  114.             {  
  115.                 Log.d("scott""" + counter);  
  116.                 counter++;  
  117.                 try  
  118.                 {  
  119.                     Thread.sleep(2000);  
  120.                 } catch (InterruptedException e)  
  121.                 {  
  122.                     e.printStackTrace();  
  123.                 }  
  124.             }  
  125.         }  
  126.     }  
  127.   
  128. }  
說明:為了表示service的確在活著,我通過打log的方式,每2s打印一次計數。上述代碼的關鍵在於onBind函數,當客戶端bind上來的時候,將IMyService.Stub mBinder返回給客戶端,這個mBinder是aidl的存根,其實現了之前定義的aidl接口中的抽象函數。

問題:問題來了,有可能你的service隻想讓某個特定的apk使用,而不是所有apk都能使用,這個時候,你需要重寫Stub中的onTransact方法,根據調用者的uid來獲得其信息,然後做權限認證,如果返回true,則調用成功,否則調用會失敗。對於其他apk,你隻要在onTransact中返回false就可以讓其無法調用IMyService中的方法,這樣就可以解決這個問題了。

4. 在AndroidMenifest中聲明service

[html] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. <service  
  2.     android:name="com.ryg.sayhi.MyService"  
  3.     android:process=":remote"  
  4.     android:exported="true" >  
  5.     <intent-filter>  
  6.         <category android:name="android.intent.category.DEFAULT" />  
  7.         <action android:name="com.ryg.sayhi.MyService" />  
  8.     </intent-filter>  
  9. </service>  

說明:上述的 <action android:name="com.ryg.sayhi.MyService" />是為了能讓其他apk隱式bindService,通過隱式調用的方式來起activity或者service,需要把category設為default,這是因為,隱式調用的時候,intent中的category默認會被設置為default。

5. 新建一個工程,充當客戶端

新建一個客戶端工程,將服務端工程中的com.ryg.sayhi.aidl包整個拷貝到客戶端工程的src下,這個時候,客戶端com.ryg.sayhi.aidl包是和服務端工程完全一樣的。如果客戶端工程中不采用服務端的包名,客戶端將無法正常工作,比如你把客戶端中com.ryg.sayhi.aidl改一下名字,你運行程序的時候將會crash,也就是說,客戶端存放aidl文件的包必須和服務端一樣。客戶端bindService的代碼就比較簡單了,如下:
[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. import com.ryg.sayhi.aidl.IMyService;  
  2. import com.ryg.sayhi.aidl.Student;  
  3.   
  4. public class MainActivity extends Activity implements OnClickListener {  
  5.   
  6.     private static final String ACTION_BIND_SERVICE = "com.ryg.sayhi.MyService";  
  7.     private IMyService mIMyService;  
  8.   
  9.     private ServiceConnection mServiceConnection = new ServiceConnection()  
  10.     {  
  11.         @Override  
  12.         public void onServiceDisconnected(ComponentName name)  
  13.         {  
  14.             mIMyService = null;  
  15.         }  
  16.   
  17.         @Override  
  18.         public void onServiceConnected(ComponentName name, IBinder service)  
  19.         {  
  20.             //通過服務端onBind方法返回的binder對象得到IMyService的實例,得到實例就可以調用它的方法了  
  21.             mIMyService = IMyService.Stub.asInterface(service);  
  22.             try {  
  23.                 Student student = mIMyService.getStudent().get(0);  
  24.                 showDialog(student.toString());  
  25.             } catch (RemoteException e) {  
  26.                 e.printStackTrace();  
  27.             }  
  28.   
  29.         }  
  30.     };  
  31.   
  32.     @Override  
  33.     protected void onCreate(Bundle savedInstanceState) {  
  34.         super.onCreate(savedInstanceState);  
  35.         setContentView(R.layout.activity_main);  
  36.         Button button1 = (Button) findViewById(R.id.button1);  
  37.         button1.setOnClickListener(new OnClickListener() {  
  38.   
  39.     @Override  
  40.     public void onClick(View view) {  
  41.         if (view.getId() == R.id.button1) {  
  42.             Intent intentService = new Intent(ACTION_BIND_SERVICE);  
  43.             intentService.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  44.             MainActivity.this.bindService(intentService, mServiceConnection, BIND_AUTO_CREATE);  
  45.         }  
  46.   
  47.     }  
  48.   
  49.     public void showDialog(String message)  
  50.     {  
  51.         new AlertDialog.Builder(MainActivity.this)  
  52.                 .setTitle("scott")  
  53.                 .setMessage(message)  
  54.                 .setPositiveButton("確定"null)  
  55.                 .show();  
  56.     }  
  57.       
  58.     @Override  
  59.     protected void onDestroy() {  
  60.         if (mIMyService != null) {  
  61.             unbindService(mServiceConnection);  
  62.         }  
  63.         super.onDestroy();  
  64.     }  
  65. }  

運行效果

可以看到,當點擊按鈕1的時候,客戶端bindService到服務端apk,並且調用服務端的接口mIMyService.getStudent()來獲取學生列表,並且把返回列表中第一個學生的信息顯示出來,這就是整個ipc過程,需要注意的是:學生列表是另一個apk中的數據,通過aidl,我們才得到的。另外,如果你在onTransact中返回false,將會發現,獲取的學生列表是空的,這意味著方法調用失敗了,也就是實現了權限認證。

最後更新:2017-04-03 12:55:35

  上一篇:go static——直屬單位
  下一篇:go slf4j-api、slf4j-log4j12以及log4j之間的關係