您的位置:首页 > 其它

Intent传递对象

2016-04-21 10:27 375 查看

Intent用途

可以借助Intent来启动活动,发送广播,启动服务等。还可以传递一些基本类型。

但是有时候我们需要传递自定义的对象。

传递自定义对象的方式

列表内容

Intent可以传递基本类型,有时候我们需要让它传递自定义的对象,

这时候就需要是要传递的对象序列化,方式有两种。

方式一: 该类实现了Serializable,可序列化的意思,表示讲一个对象转换成可存储或可传输的状态。

序列化对的对象可以在网络上传输,也可以存储到本地。

//列如要序列化一个person对象,只需要实现Serializable 接口就行了。
public class Person implements Serializable{

String name;
int age;

public String getName() {
return name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public void setName(String name) {
this.name = name;
}

}


启动活动时发送对象

void sendIntent(Context context){

Person person = new Person();
person.setName("王老五");
person.setAge(40);

Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("person_data",person);
context.startActivity(intent);

}


从Intent中取出对象

/**
* 在第二个Activity中得到传递过来的对象
* */

void getIntent(Activity activity){

Person person = (Person)activity.getIntent().getSerializableExtra("person_data");

}


Parcelable方式

除Serializable之外,Parcelable也有相似的效果,不同于将对象序列化。

Parcelable是将一个完整的对象进行分解,而分解后的每一部分都是Intent所支持的数据类型。

public class Person2 implements Parcelable {
String name;
int age;

protected Person2() {

}
public String getName() {
return name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public void setName(String name) {
this.name = name;
}
@Override
public int describeContents() {
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);//写出name
dest.writeInt(age);//写出age
}

public static final Creator<Person2> CREATOR = new Creator<Person2>() {
@Override
public Person2 createFromParcel(Parcel in) {
Person2 person = new Person2();

person.name = in.readString();//读取出name
person.age = in.readInt();//读取出age

return  person;
}

@Override
public Person2[] newArray(int size) {
return new Person2[size];
}
};

}


发送使用Parcelable序列化的对象,和 Serializable的一样

“`

Person2 person = new Person2();
person.setName("小瘪三");
person.setAge(40);

Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("person_data",person);
context.startActivity(intent);


- 从Intent中取出对象,和Serializable 有些不同


Person2 person2 =

(Person2)activity.getIntent().getParcelableExtra(“person_data”);

“`

Parcelable 的实现方式比较复杂一些,需要重新describeContents() 和 writeToParcel(Parcel dest, int flags)的方法。

而在writeToParcel()方法中需要将字段一一 写出. 注意字段的类型。

还有提供一个字段 CREATOR ,并将这些写入的东西一一读出,读出的方法

都是调用Parcel 的 readXXX来读取到。

注意 这里读取到的东西要和写入的顺序一致。并创建一个对象,将这个对象返回。

Serializable 和 Parcelable 的比较

Serializable 会把整个对象进行序列化,因此效率会比 Parcelable 低一些。

通常情况下还是更推荐使用Parcelable 方式来实现Intent传递对象的功能。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  序列化-Intent