Android Service學習之AIDL, Parcelable和遠程服務

 由於每個應用程序都運行在自己的進程空間,並且可以從應用程序UI運行另一個服務進程,而且經常會在不同的進程間傳遞對象。在Android平臺,一 個進程通常不能訪問另一個進程的內存空間,所以要想對話,需要將對象分解成操作系統可以理解的基本單元,並且有序的通過進程邊界。
    通過代碼來實現這個數據傳輸過程是冗長乏味的,Android提供了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。


    在設計AIDL接口前,要提醒的是,調用AIDL接口是直接的方法調用的,不是我們所想象的調用是發生在線程裏。而調用(call)來自local進程或者remote進程,有什麼區別呢?尤其是以下情況(引用原文,不作翻譯了,以免翻譯有誤):


?Calls made from the local process are executed in the same thread that is making the call. If this is your main UI thread, that thread continues to execute in the AIDL interface. If it is another thread, that is the one that executes your code in the service. Thus, if only local threads are accessing the service, you can completely control which threads are executing in it (but if that is the case, then you shouldn't be using AIDL at all, but should instead create the interface by implementing a Binder ).
?Calls from a remote process are dispatched from a thread pool the platform maintains inside of your own process. You must be prepared for incoming calls from unknown threads, with multiple calls happening at the same time. In other words, an implementation of an AIDL interface must be completely thread-safe.
?The oneway keyword modifies the behavior of remote calls. When used, a remote call does not block; it simply sends the transaction data and immediately returns. The implementation of the interface eventually receives this as a regular call from the Binder thread pool as a normal remote call. If onewayis used with a local call, there is no impact and the call is still synchronous.




定義AIDL接口
    AIDL接口文件,和普通的接口內容沒有什麼特別,只是它的擴展名爲.aidl。保存在src目錄下。如果其他應用程序需要IPC,則那些應用程序的src也要帶有這個文件。 Android SDK tools就會在gen目錄自動生成一個IBinder接口文件。service必須適當地實現這個IBinder接口。那麼客戶端程序就能綁定這個service並在IPC時從IBinder調用方法。
    每個aidl文件只能定義一個接口,而且只能是接口的聲明和方法的聲明。


1.創建.aidl文件 
     AIDL使用簡單的語法來聲明接口,描述其方法以及方法的參數和返回值。這些參數和返回值可以是任何類型,甚至是其他AIDL生成的接口。
    其中對於Java編程語言的基本數據類型 (int, long, char, boolean等),String和CharSequence,集合接口類型List和Map,不需要import 語句。
    而如果需要在AIDL中使用其他AIDL接口類型,需要import,即使是在相同包結構下。AIDL允許傳遞實現Parcelable接口的類,需要import.
    需要特別注意的是,對於非基本數據類型,也不是String和CharSequence類型的,需要有方向指示,包括in、out和inout,in表示由客戶端設置,out表示由服務端設置,inout是兩者均可設置。
    AIDL只支持接口方法,不能公開static變量。 


例如 (IMyService.aidl): 


01.package com.demo; 


02.


03.import com.demo.Person; 


04.


05.interface IMyService { 


06.        void savePersonInfo(in Person person); 


07.        List<Person> getAllPerson(); 


08.}
複製代碼2.實現接口
    創建一個類實現剛纔那個aidl的接口:


01.public class RemoteService extends Service { 


02.


03.        private LinkedList<Person> personList = new LinkedList<Person>(); 


04.         


05.        @Override 


06.        public IBinder onBind(Intent intent) { 


07.                return mBinder; 


08.        } 


09.


10.        private final IMyService.Stub mBinder = new IMyService.Stub() { 


11.


12.                @Override 


13.                public void savePersonInfo(Person person) throws RemoteException { 


14.                        if (person != null ){ 


15.                                personList.add(person); 


16.                        } 


17.                } 


18.


19.                @Override 


20.                public List<Person> getAllPerson() throws RemoteException { 


21.                        return personList; 


22.                } 


23.        }; 


24.}
複製代碼這裏會看到有一個名爲IMyService.Stub類,查看aidl文件生成的Java文件源代碼就能發現有這麼一段代碼:
01./** Local-side IPC implementation stub class. */ 


02.public static abstract class Stub extends android.os.Binder implements com.demo.IMyService
複製代碼原來Stub類就是繼承於Binder類,也就是說RemoteService類和普通的Service類沒什麼不同,只是所返回的IBinder對象比較特別,是一個實現了AIDL接口的Binder。


    接下來就是關於所傳遞的數據Bean——Person類,是一個序列化的類,這裏使用Parcelable 接口來序列化,是Android提供的一個比Serializable 效率更高的序列化類。
    Parcelable需要實現三個函數:
    1) void writeToParcel(Parcel dest, int flags) 將需要序列化存儲的數據寫入外部提供的Parcel對象dest。而看了網上的代碼例子,個人猜測,讀取Parcel數據的次序要和這裏的write次序一致,否則可能會讀錯數據。具體情況我沒試驗過!
    2) describeContents() 沒搞懂有什麼用,反正直接返回0也可以
    3) static final Parcelable.Creator對象CREATOR  這個CREATOR命名是固定的,而它對應的接口有兩個方法:
    createFromParcel(Parcel source) 實現從source創建出JavaBean實例的功能


    newArray(int size) 創建一個類型爲T,長度爲size的數組,僅一句話(return new T[size])即可。估計本方法是供外部類反序列化本類數組使用。
  
仔細觀察Person類的代碼和上面所說的內容:


01.public class Person implements Parcelable { 


02.


03.        private String name; 


04.        private String telNumber; 


05.        private int age; 


06.


07.        public Person() {} 


08.


09.        public Person(Parcel pl){ 


10.                name = pl.readString(); 


11.                telNumber = pl.readString(); 


12.                age = pl.readInt(); 


13.        } 


14.


15.        public String getName() { 


16.                return name; 


17.        } 


18.


19.        public void setName(String name) { 


20.                this .name = name; 


21.        } 


22.


23.        public String getTelNumber() { 


24.                return telNumber; 


25.        } 


26.


27.        public void setTelNumber(String telNumber) { 


28.                this .telNumber = telNumber; 


29.        } 


30.


31.        public int getAge() { 


32.                return age; 


33.        } 


34.


35.        public void setAge(int age) { 


36.                this .age = age; 


37.        } 


38.


39.        @Override 


40.        public int describeContents() { 


41.                return 0; 


42.        } 


43.


44.        @Override 


45.        public void writeToParcel(Parcel dest, int flags) { 


46.                dest.writeString(name); 


47.                dest.writeString(telNumber); 


48.                dest.writeInt(age); 


49.        } 


50.


51.        public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() { 


52.


53.                @Override 


54.                public Person createFromParcel(Parcel source) { 


55.                        return new Person(source); 


56.                } 


57.


58.                @Override 


59.                public Person[] newArray(int size) { 


60.                        return new Person[size]; 


61.                } 


62.


63.        }; 


64.}


65.
複製代碼然後創建Person.aidl文件,注意這裏的parcelable和原來實現的Parcelable 接口,開頭的字母p一個小寫一個大寫:
01.package com.demo; 


02.


03.parcelable Person;
複製代碼對於實現AIDL接口,官方還提醒我們:
    1. 調用者是不能保證在主線程執行的,所以從一調用的開始就需要考慮多線程處理,以及確保線程安全;
    2. IPC調用是同步的。如果你知道一個IPC服務需要超過幾毫秒的時間才能完成地話,你應該避免在Activity的主線程中調用。也就是IPC調用會掛起應用程序導致界面失去響應,這種情況應該考慮單獨開啓一個線程來處理。
    3. 拋出的異常是不能返回給調用者(跨進程拋異常處理是不可取的)。


3. 客戶端獲取接口
    客戶端如何獲取AIDL接口呢?通過IMyService.Stub.asInterface(service)來得到IMyService對象:


01.private IMyService mRemoteService; 


02.


03.private ServiceConnection mRemoteConnection = new ServiceConnection() {    


04.        public void onServiceConnected(ComponentName className, IBinder service) {    


05.                mRemoteService = IMyService.Stub.asInterface(service);     


06.        }    


07.


08.        public void onServiceDisconnected(ComponentName className) {    


09.                mRemoteService = null ;    


10.        }    


11.};
複製代碼在生成的IMyService.java裏面會找到這樣的代碼:
01./** 


02.* Cast an IBinder object into an com.demo.IMyService interface, 


03.* generating a proxy if needed. 


04.*/ 


05.public static com.demo.IMyService asInterface(android.os.IBinder obj) {...}
複製代碼而service的綁定沒有什麼不同:
01.if (mIsRemoteBound) { 


02.        unbindService(mRemoteConnection); 


03.}else { 


04.        bindService(new Intent("com.demo.IMyService" ), 


05.                               mRemoteConnection , Context.BIND_AUTO_CREATE); 


06.} 


07.


08.mIsRemoteBound = !mIsRemoteBound;
複製代碼通過IPC調用/傳遞數據
    客戶端綁定service後就能通過IPC來調用/傳遞數據了,直接調用service對象的接口方法:


01.addPersonButton.setOnClickListener( 


02.                new View.OnClickListener(){ 


03.                        private int index = 0; 


04.


05.                        @Override 


06.                        public void onClick(View view) { 


07.                                Person person = new Person(); 


08.                                index = index + 1; 


09.                                person.setName("Person" + index); 


10.                                person.setAge(20); 


11.                                person.setTelNumber("123456" ); 


12.                                try { 


13.                                        mRemoteService.savePersonInfo(person); 


14.                                } catch (RemoteException e) { 


15.                                        e.printStackTrace(); 


16.                                } 


17.                        } 


18.                }); 


19.


20.listPersonButton.setOnClickListener( 


21.                new View.OnClickListener(){ 


22.


23.                        @Override 


24.                        public void onClick(View view) { 


25.                                List<Person> list = null ; 


26.


27.                                try { 


28.                                        list = mRemoteService.getAllPerson(); 


29.                                } catch (RemoteException e) { 


30.                                        e.printStackTrace(); 


31.                                } 


32.


33.                                if (list != null ){ 


34.                                        StringBuilder text = new StringBuilder(); 


35.


36.                                        for (Person person : list){ 


37.                                                text.append("/nPerson name:" ); 


38.                                                text.append(person.getName()); 


39.                                                text.append("/n             age :" ); 


40.                                                text.append(person.getAge()); 


41.                                                text.append("/n tel number:" ); 


42.                                                text.append(person.getTelNumber()); 


43.                                        } 


44.


45.                                        inputPersonEdit.setText(text); 


46.                                }else { 


47.                                        Toast.makeText(ServiceActivity.this , "get data error" , 


48.                                                        Toast.LENGTH_SHORT).show(); 


49.                                } 


50.                        } 


51.                });
複製代碼Permission權限 
    如果Service在AndroidManifest.xml中聲明瞭全局的強制的訪問權限,其他引用必須聲明權限才能來start,stop或bind這個service.
     另外,service可以通過權限來保護她的IPC方法調用,通過調用checkCallingPermission(String)方法來確保可以執行這個操作。


AndroidManifest.xml的Service元素


01.< service android:name =".RemoteService" android:process =":remote" > 


02.        < intent-filter > 


03.                < action android:name ="com.demo.IMyService" /> 


04.        </ intent-filter > 


05.</ service >
複製代碼這裏的android:process=":remote",一開始我沒有添加的,在同一個程序裏使用IPC,即同一個程序作爲客戶端/服務器端,結果運 行mRemoteService = IMyService.Stub.asInterface(service);時提示空指針異常。觀察了人家的在不同程序裏進行IPC的代碼,也是沒有這 個android:process=":remote"的。後來在官方文檔http://androidappdocs.appspot.com/guide/topics/manifest/service-element.html 裏瞭解到(留意第二段文字):android:processThe name of the process where the service is to run. Normally, all components of an application run in the default process created for the application. It has the same name as the application package. The <application> element's process attribute can set a different default for all components. But component can override the default with its own process attribute, allowing you to spread your application across multiple processes.


也就是說android:process=":remote",代表在應用程序裏,當需要該service時,會自動創建新的進程。而如果是android:process="remote",沒有“:”分號的,則創建全局進程,不同的應用程序共享該進程。If the name assigned to this attribute begins with a colon (':'), a new process, private to the application, is created when it's needed and the service runs in that process . If the process name begins with a lowercase character, the service will run in a global process of that name, provided that it has permission to do so. This allows components in different applications to share a process, reducing resource usage.

《轉》
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章