之前intent傳值,用到過Serializable和Parcelable,但並沒有真正的理解,鞏固之前
Intent在不同的組件中傳遞對象數據的應用非常普遍。下面介紹兩種通過Intent傳遞對象的方法。
1、實現Serializable接口
2、實現Parcelable接口
爲什麼要將對象序列化?
1、永久性保存對象,保存對象的字節序列到本地文件中;
2、用過序列化對象在網絡中傳遞對象;
3、通過序列化對象在進程間傳遞對象。
1、實現Serializable接口
Serializable的作用是將數據對象存入字節流當中,在需要時重新生成對象,主要應用是利用外部存儲設備保存對象狀態,以及通過網絡傳輸對象等。
implements Serializable接口的的作用就是給對象打了一個標記,系統會自動將其序列化。
案例1:
1)User.java (implements Serializable )
2)MainActivity.java
User user = new User();
Intent intent = new Intent(this,Second.class);
intent.putExtra("user",user);
3)Second.java
Intent intent = getIntent();
User user = intent.getSerializableExtra("user");
2、實現Parcelable接口
1)爲什麼要實現Parfcelable接口來實現在Intent中傳遞對象?
a、在使用內存的時候,Parcelable比Serializable性能高,所以推薦使用Parcelable類。
b、Serializable在序列化的時候會產生大量的臨時變量,從而引起頻繁的GC。
注意:Parcelable不能使用在將數據存儲在磁盤上的情況,因爲Parcelable不能很好的保存數據的持續性在外界有變化的情況下。因此在這種情況下,建議使用Serializable
2) Android中的新的序列化機制
在Android系統中,針對內存受限的移動設備,因此對性能要求更高,Android系統採用了新的IPC(進程間通信)機制,要求使用性能更出色的對象傳輸方式。因此Parcel類被設計出來,其定位就是輕量級的高效的對象序列化和反序列化機制。
Parcel的序列化和反序列化的讀寫全是在內存中進行,所以效率比JAVA序列化中使用外部存儲器會高很多。
Parcel類
就應用程序而言,在常使用Parcel類的場景就是在Activity間傳遞數據。在Activity間使用Intent傳遞數據的時候,可以通過Parcelable機制傳遞複雜的對象。
Parcel機制:本質上把它當成一個Serialize就可以了。只是Parcel的對象實在內存中完成的序列化和反序列化,利用的是連續的內存空間,因此更加高效。
案例:
步驟1:自定義實體類,實現Parcelable接口,重寫其兩個方法。
步驟2:該實體類必須添加一個常量CREATOR(名字大小寫都不能使其他的),該常量必須實現Parcelable的內部接口:Parcelable.Creator,並實現該接口中的兩個方法。
User.java如下:
import android.os.Parcelable;
public String name;
public int age;
public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() {
@Override
public User createFromParcel(Parcel source) {
return new User(source);
}
//重寫createFromParcel方法,創建並返回一個獲得了數據的user對象
@Override
public User[] newArray(int size) {
return new User[size];
}
};
public String toString() {
return name + ":" + age;
}
public User() {
}
private User(Parcel source) {
name = source.readString();
age = source.readInt();
}
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
}
具體應用
Bundle bundle = new Bundle();
bundle.putParcelable("user", user);
Intent intent = new Intent(MainActivity.this,
SecondActivity.class);
intent.putExtras(bundle);
Intent intent = getIntent();
Bundle bun = intent.getExtras();
User user = bun.getParcelable("user");
System.out.println(user);