腦圖鏈接:http://naotu.baidu.com/file/ac4586250dc8e89909b6021acbe81faf?token=547626ceb7336446
2.1 Android IPC簡介
線程與進程
線程是CPU調(diào)度的最小單元。
進程一般指一個執(zhí)行單元,在PC和移動設備上只一個程序或者一個應用。
一個進程可以包含多個線程。
2.2 Android中的多進程模式
2.2.1 開啟多進程模式
不考慮通過JNI在native層去fork新進程這種特殊方法的情況下撮执,
在Android中使用多進程只有一種方法,那就是給四大組件在Menifest中指定 android:process屬性舷丹。
2.2.2 多進程模式的運行機制
Android會為每個進程都分配一個獨立的虛擬機二打,不同的虛擬機在內(nèi)存分配上有不同的地址空間,這就導致在不同的虛擬機中訪問同一個類對象會產(chǎn)生多份副本掂榔。
所有運行在不同進程中的四大組件继效,只要他們之間需要通過內(nèi)存來共享數(shù)據(jù),都會共享失敗装获。
使用多進程會造成如下幾方面的問題:
- 靜態(tài)成員和單例模式完全失效瑞信。
- 線程同步機制完全失效。
- SharedPreferences的可靠性下降穴豫。
- Application會多次創(chuàng)建凡简。
跨進程通訊方式
Intent傳遞數(shù)據(jù)
共享文件
SharedPreferences
基于Binder的Messenger和AIDL
Socket
2.3 IPC基礎概念介紹
Serializable和Parcelable接口可以完成對象的序列化過程逼友。、
靜態(tài)成員變量屬于類不屬于對象秤涩,所以不參與序列化過程帜乞;
用transient關鍵字標記的成員變量不參與序列化過程;
2.3.1 Serializable接口
private static final long serialVersionUID = 1231231231231242L;
serialVersionUID如果不手動指定筐眷,系統(tǒng)會計算當前類的hash值復制給它黎烈,如果類發(fā)生變化,serialVersionUID就會改變匀谣,導致反序列化失敗照棋。
手動指定serialVersionUID可以很大程度的減少此種情況的發(fā)生。
2.3.2 Parcelable接口
public @ContentsFlags int describeContents();
/**
* Flatten this object in to a Parcel.
*
* @param dest The Parcel in which the object should be written.
* @param flags Additional flags about how the object should be written.
* May be 0 or {@link #PARCELABLE_WRITE_RETURN_VALUE}.
*/
public void writeToParcel(Parcel dest, @WriteFlags int flags);
/**
* Interface that must be implemented and provided as a public CREATOR
* field that generates instances of your Parcelable class from a Parcel.
*/
public interface Creator<T> {
/**
* Create a new instance of the Parcelable class, instantiating it
* from the given Parcel whose data had previously been written by
* {@link Parcelable#writeToParcel Parcelable.writeToParcel()}.
*
* @param source The Parcel to read the object's data from.
* @return Returns a new instance of the Parcelable class.
*/
public T createFromParcel(Parcel source);
/**
* Create a new array of the Parcelable class.
*
* @param size Size of the array.
* @return Returns an array of the Parcelable class, with every entry
* initialized to null.
*/
public T[] newArray(int size);
}
Serilizable Parcelable對比
Serilizable是java的序列化接口武翎,使用簡單烈炭,開銷大。
Parcelable是Android序列化接口宝恶,使用復雜(IDE自動生成就問題不大了)符隙,開銷小,推薦使用垫毙。
Parcelable主要用在內(nèi)存序列化上膏执,本地存儲、網(wǎng)絡傳輸稍顯復雜露久,建議使用Serializable。
2.3.3 Binder
Binder是Android中的一個類欺栗,實現(xiàn)了IBinder接口毫痕。
從IPC角度來說,Binder是Android中的一種跨進程通信方式迟几,Binder還可以理解為一種虛擬的物理設備消请,他的設備驅(qū)動是/dev/binder,該通信方式在Linux中沒有类腮;
從Android Framwork角度來說臊泰,Binder是ServiceManager連接各種Manager(ActivityManager、WindowManager蚜枢,等等)和響應ManagerService的橋梁缸逃;
從Android應用層來說,Binder是客戶端和服務端進行通信的媒介厂抽,當bindService的時候需频,服務端會返回一個包含了服務端業(yè)務調(diào)用的Binder對象,通過這個Binder對象筷凤,客戶端就可以獲取五福短提供的服務或者數(shù)據(jù)昭殉,這里的服務包括普通服務和基于AIDL的服務苞七。