本文執行個體分析了Android編程使用Intent傳遞對象的方法。分享給大家供大家參考,具體如下:
之前的文章中,介紹過Intent的用法,比如啟動活動,發送廣播,啟發服務等,並且可以使用Intent時傳遞一些資料。如下代碼所示:
Intent intent = new Intent(this,SecondActivity.class);intent.putExtra("info", "I am fine");startActivity(intent);
在傳遞資料時,使用的方法是putExtra,支援的資料類型有限,如何傳遞對象呢??
在Android中,使用Intent傳遞對象有兩種方式:Serializable序列化方式以及Parcelable序列化方式。
1、Serializable方式
此種方式表示將一個對象轉換成可儲存或者可傳輸的狀態,序列化後的對象可以在網路上進行傳輸,可以儲存到本地。
對象序列化,只需要實現Serializable類。
package com.example.testapplication;import java.io.Serializable;/** * 對象序列化 * @author yy * */public class Emp implements Serializable { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }}
那麼Intent如何傳遞對象參數呢,查看API發現如下方法:
複製代碼 代碼如下:
intent.putExtra(String name, Serializable value);
因此,使用該方法傳遞,如下:
Intent intent = new Intent(this,SecondActivity.class);intent.putExtra("obj", new Emp());startActivity(intent);
那麼如何擷取呢?使用如下方法:
複製代碼 代碼如下:
Emp emp = (Emp) getIntent().getSerializableExtra("obj");
這樣就獲得了Emp對象了。
2、Parcelable方式
該種方式的實現原理是將一個完整的對象進行分解,使分解的每一部分都是Intent所支援的資料類型。樣本如下:
package com.example.testapplication;import android.os.Parcel;import android.os.Parcelable;/** * Parcelable方式 * @author yy * */public class Emp2 implements Parcelable{ private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flag) { //寫出name dest.writeString(name); //寫出age dest.writeInt(age); } public static final Parcelable.Creator<Emp2> creator = new Creator<Emp2>() { @Override public Emp2[] newArray(int size) { return new Emp2[size]; } @Override public Emp2 createFromParcel(Parcel source) { Emp2 emp2 = new Emp2(); //讀取的順序要和上面寫出的順序一致 //讀取name emp2.name = source.readString(); emp2.age = source.readInt(); return emp2; } };}
傳遞對象:方式和序列化相同:
Intent intent = new Intent(this,SecondActivity.class);intent.putExtra("obj", new Emp2());startActivity(intent);
擷取對象:
複製代碼 代碼如下:
Emp2 emp2 = getIntent().getParcelableExtra("obj");
3、區別
Serializable在序列化的時候會產生大量的臨時變數,從而引起頻繁的GC。因此,在使用記憶體的時候,Parcelable 類比Serializable效能高,所以推薦使用Parcelable類。
Parcelable不能使用在要將資料存放區在磁碟上的情況,因為Parcelable不能很好的保證資料的持久性在外界有變化的情況下。儘管Serializable效率低點, 也不提倡用,但在這種情況下,還是建議你用Serializable 。
希望本文所述對大家Android程式設計有所協助。