现在的位置: 首页 > 综合 > 正文

如何使用Intent传递对象

2019年08月15日 ⁄ 综合 ⁄ 共 1158字 ⁄ 字号 评论关闭

如何使用Intent传递对象

我们可以使用Intent来启动Activity,开启服务Service,发送广播Broadcast,然后使用Intent传递基本的数据类型,如:布尔值,整型,字符串等

Intent intent = new Intent(this, SecondActivyt.class);
intent.putExtra("isBoy", true);
intent.putExtra("age", 24);
intent.putExtra("name", "jane");

如果我们想用Intent传递对象,那么这个传递的对象是可序列化的。Serializable 是序列化的意思,表示将一个对象转换成可存储或可传输的状态。序列化后的对象可以在网络上进行传输,也可以存储到本地。至于序列化的方法也很简单,只需要让一个类去实现 Serializable 这个接口就可以了。

public class Person implements Serializable {
	private String name;
	private String password;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public Person() {
		super();
	}
	public Person(String name, String password) {
		super();
		this.name = name;
		this.password = password;
	}
}

这里因为Person 实现了Serialable接口,所以所有的Person对象都是可序列化的。这时我们就可以使用Intent来传递Person对象了。

Person person = new Person("wk","123");
Intent intent = new Intent(this, SecondActivyt.class);
intent.putExtra("person_data", person);
startActivity(intent);

在SecondActivity中,我们就可以获取Person对象了

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

getSerializableExtra()方法来获取通过参数传递过来的序列化对象,这样我们就获取到了person对象,实现了使用intent传递对象的功能。



抱歉!评论已关闭.