标签:传递 ble contents getname style bec source desc stat
序列化:将对象转换为可以传输的二进制流的过程。
Serializable是 Java 提供的一个标准化的序列化接口。
Parcelable是 Android 提供的序列化接口。(效率更高)
比如一个Person类,想要将它序列化,Serializable只需实现接口,然后进行传递即可。
Parcelable方式
采用Parcelable需要实现接口,以及重写desrcibeContents() 和writeToParcel(...)方法,添加一个名为CREATOR的常量(即描述、序列化、反序列化)。
public class Person implements Parcelable { 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; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); dest.writeInt(age); } public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() { @Override public Person createFromParcel(Parcel source) { Person person = new Person(); person.name = source.readString(); person.age = source.readInt(); return person; } @Override public Person[] newArray(int size) { return new Person[size]; } }; }
传递Person对象的方式 二者相同
Person person =new Person(); person.setName("Tom"); person.setAge(20); Intent intent = new Intent(MainActivity.this, SecondActivity.class); intent.putExtra("person_data", person); startActivity(intent);
Serializable获取对象方式
Person person = (Person) getIntent().getSerializableExtra("person_data");
Parcelable获取对象方式
Person person = (Person) getIntent().getParcelableExtra("person_data");
标签:传递 ble contents getname style bec source desc stat
原文地址:https://www.cnblogs.com/kyun/p/10008984.html