如何使用Intent传递对象

如何使用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传递对象的功能。



  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值