Intent還是很有用的一個好東西,可以幫我們啟動活動、發送廣播、啟動服務等等。但是它并不是這么簡單,它能耍一耍傳遞數據的花活。
傳遞簡單的數據
比如說,我們可以在某一個活動中定義這樣一個intent:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("a string", "hello world");
intent.putExtra("a int", 123);
startActivity(intent);
然后,我們可以在第二個活動這樣獲取上例中的數據:
getIntent().getStringExtra("a string");
getIntent().getIntExtra("a int", 0);
可以看到,數據傳遞還是很簡單的,也很容易理解,需要說明的時,putExtra函數的參數是以鍵值對的方式給出的,getIntExtra函數的第二個參數是默認值,也就是不能成功獲取數據的時候的函數返回值,可以隨便寫啦。但是嘞,這種方法傳遞的數據類型還是很有限的,當我么需要傳遞自定義的數據類型的時候,就會很捉急!燃鵝不用擔心,我們還有更多的技巧用來傳遞數據。
Serializable方式
Serializable即序列化,意思就是將一個對象轉換成可存儲或者可傳輸的狀態。具體的實現方法是讓一個類去實現Serializable這個接口。
public class Person 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中加入數據的時候就可以這樣寫了:
Person person = new Person();
person.setName("Tom");
person.setAge(24);
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("person data", person);
startActivity(intent);
數據的獲取也就不一樣咯:
Person person = (Person) getIntent().getSerializableExtra("person data");
這里調用了getSerializableExtra()函數來獲取通過參數傳遞過來的序列化對象,接著再將它向下轉型為Person對象,這樣我們就成功實現了利用intent來傳遞對象的功能啦!
Parcelable方式
Parcelable的實現原理是將一個完整的對象進行分解,而分解之后的每一部分都是Intent可以傳遞的數據類型。代碼實現:
public class Person 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 test, int flags) {
test.writeString(name);
test.writeInt(age);
}
public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
@Override
public Person createFromParcel(Parcel source) {
Person person = new Person();
person.name = source.readString(); //讀取name
person.age = source.readInt(); //讀取age
return person;
}
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
}
復雜……好煩……是不是……但是!這種方法的效率會比前者更高,因為它沒有將整個對象序列化。所以,還是推薦使用這種方法。
??首先,也是實現接口,然后重寫了兩個函數describeContents()和writeToParcel()。尤其是第二個函數,要在這里面將類的各個字段一一寫出。我們還必須在Person類中提供一個名為CREATE的常量。數據的加載方式不變,具體的獲取數據的方法基本一致,只不過換了個名字:
Person person = (Person) getIntent().getParcelableExtra("person data");