Android provides a type: Parcel. It is used as a container to encapsulate data. The encapsulated data can be delivered through Intent or IPC. In addition to basic types, only classes that implement the Parcelable interface can be put into Parcel.
Key points of Parcelable implementation: three things need to be implemented
1) writeToParcel method. This method writes the data of the class into an externally provided Parcel. It is declared as follows:
writeToParcel (Parcel dest, int flags) See javadoc for specific parameter meanings
2) describeContents method. I don’t understand what the use is. Anyway, you can just return 0.
3) Static Parcelable.Creator interface. This interface has two methods:
createFromParcel(Parcel in) implements the function of creating an instance of the class from in
newArray(int size) creates an array of type T and length size, just one sentence (return new T[size]) is enough. It is estimated that this method is used by external classes to deserialize arrays of this class.
Activity for receiving information for testing:
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState) ; setContentView(R.layout.main); Intent i = getIntent(); Person p = i.getParcelableExtra("yes"); System.out.println("---->"+p.name); System.out.println("---->"+p.map.size()) ; } }
Activity sent:
import java.util.HashMap; import android.app.Activity; import android.content.Intent; import android.os.Bundle; public class TestNew extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState) ; setContentView(R.layout.main); Intent intent = new Intent(); Person p = new Person(); p.map = new HashMap<String,String>(); p.map.put("yes", "ido"); p.name="ok"; intent.putExtra("yes", p); intent.setClass(this, Test .class); startActivity(intent); } }
Parcelable implementation class:
import java.util.HashMap; import android.os.Parcel; import android.os.Parcelable; public class Person implements Parcelable { public HashMap<String,String> map = new HashMap<String,String> (); public String name; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeMap(map); dest.writeString(name); } public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() { //Override Creator @Override public Person createFromParcel(Parcel source) { Person p = new Person(); p.map=source.readHashMap(HashMap.class.getClassLoader()); p.name=source.readString(); return p; } @Override public Person[] newArray(int size) { // TODO Auto-generated method stub return null; } }; }