怎样使用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 是序列化的意思,表示将一个对象转换成可存储或可传输的状态。序列化后的对象能够在网络上进行传输,也能够存储到本地。至于序列化的方法也非常easy,仅仅须要让一个类去实现 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传递对象的功能。