Android跨進程通信:通過Intent來傳遞數(shù)據(jù),共享文件和SharedPreference跌前,基于Binder的Messenger和AIDL以及Socket棕兼。
IPC基礎(chǔ)概念介紹:
1、Serializable接口:Serializable是java提供的一個序列化接口抵乓,它是一個空接口伴挚,為對象提供標(biāo)準(zhǔn)的序列化和反序列化操作。
User類:
public class User {
private static final long serialVersionUID = 519067123721295773L;
public int userId;
public String userName;
public boolean isMale;
public User(int userId, String userName, boolean isMale) {
this.userId = userId;
this.userName = userName;
this.isMale = isMale;
}
}
序列化過程:
User user = new User(0, "jake", true);
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("cache.txt"));
out.writeObject(user);
out.close();
反列化過程:
ObjectInputStream in = new ObjectInputStream(new FileInputStream("cache.txt"));
User newUser = (User)in.readObject();
in.close();
只要把實現(xiàn)了Serializable接口的User對象寫到文件中就可以快速恢復(fù)了灾炭,恢復(fù)后的對象newUser和user內(nèi)容完全一樣茎芋,但是兩者并不是一個對象。如果之前沒有指定serializableUID也是可以實現(xiàn)序列化蜈出,但是不能保證類的內(nèi)容败徊、成員變量是否一樣。所以最好需要指定一個掏缎,可以手動指定皱蹦。也可以重寫系統(tǒng)默認(rèn)的序列化過程。
2眷蜈、Parcelable接口:Android提供的序列化接口沪哺。
public class UserProcelable implements Parcelable {
public int userId;
public String userName;
public boolean isMale;
public Book book;
public UserProcelable(int userId, String userName, boolean isMale) {
this.userId = userId;
this.userName = userName;
this.isMale = isMale;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(userId);
out.writeSerializable(userName);
out.writeInt(isMale ? 1 : 0);
out.writeParcelable(book, 0);
}
public static final Parcelable.Creator<UserProcelable> CREATOR = new Parcelable.Creator<UserProcelable>() {
public UserProcelable createFromParcel(Parcel in) {
return new UserProcelable(in);
}
public UserProcelable[] newArray(int size) {
return new UserProcelable[size];
}
};
private UserProcelable(Parcel in) {
userId = in.readInt();
userName = in.readString();
isMale = in.readInt() == 1;
book = in.readParcelable(Thread.currentThread().getContextClassLoader());
}
}
在上面代碼中,Parcel內(nèi)部包裝了可序列化的數(shù)據(jù)酌儒,可以在Binder中自由傳輸辜妓。
在序列化過程也能夠中需要實現(xiàn)的功能有序列化、反序列化和內(nèi)容描述忌怎。
序列化由writeToParcel方法完成籍滴,最終通過Parcel中的方法完成。
反序列化由CREATOR來完成榴啸,其內(nèi)部標(biāo)明了如何創(chuàng)建序列化對象和數(shù)組孽惰,也是通過Parcel中的方法完成反序列化。
內(nèi)容描述由describeContents方法完成鸥印,基本上都返回0勋功。
其中Book是另外一個可序列化對象坦报。
上述兩種方法的區(qū)別:
Serializable是java中的接口,需要大量的IO操作狂鞋,實現(xiàn)簡單片择。
Paracel是Android中的接口,實現(xiàn)麻煩骚揍,但是效率高字管。
如果要涉及到將信息序列化后存儲到硬盤或者通過網(wǎng)絡(luò)傳輸,還是推薦使用Serializable信不,否則一般情況下推薦使用Paracel