Intent我们可以用来启动活到,发送广播,启动服务等,还可以在intent中添加一个数据达到传值的效果。但是Intent的传值支持的类型有限。
Intent来传递对象的方式有:Serializable和parcelable
Serializable
serializable是序列化的意思,把一个对象转化为可存储可传输的状态。序列化的方式就是创建一个类实现Serializable这个接口。
比如Person类包含name和age,想把它序列化
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;
}
}
接下来在FirstActivity使用就非常简单了
Person person = new Person();
person.setName("Tom");
person.setAge(18);
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("person1",person);
startActivity(intent);
在SecondActivity取出对象
序列化对象向下转型为Person对象
Person person=(Person)getIntent().getSerializableExtra("person1");
Parcelable
不同于将对象序列化.Parceable是将一个完整的对象进行分解,而分解后的每一部分都是Intent所支持的数据类型.
Person类实现Parcelable 接口
public class Person implements Parcelable {
private String name;
private int age;
public Person() {
}
public static final Creator<Person> CREATOR = new Creator<Person>() {
@Override
public Person createFromParcel(Parcel in) {
Person person = new Person();
person.name=in.readString();
person.age=in.readInt();
return person;
}
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
}
}