Thực hiện Parcelable qua AIDL
Bước đầu tiên: - Tạo một file .aidl khác nhau sẽ được sử dụng cho định nghĩa class Student (lớp Parcelable).
(Student.aidl)
package com.aidl;
parcelable Student;
chúng tôi viết thư này vì aidl có thể phát hiện Lớp học sinh.
Bước thứ hai: - bây giờ bạn phải xác định một lớp java với tên sinh viên và triển khai giao diện parcable trong lớp này. giao diện parcable có hai phương thức trừu tượng mà bạn phải thực hiện trong lớp học của bạn.
import android.os.Parcel;
import android.os.Parcelable;
public class Student implements Parcelable {
public String name;
public String father_name;
public Student(Parcel source)
{
name = source.readString();
father_name = source.readString();
}
public Student()
{}
public void setName(String name)
{
this.name = name;
}
public void setFatherName(String father_name)
{
this.father_name = father_name;
}
// phương pháp giao diện parcable
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString(name);
dest.writeString(father_name);
}
Trong bất kỳ lớp được thực hiện Parcelable phải cung cấp lĩnh vực CREATOR. Loại CREATOR phải là Parcelable.Creator. Ở đây thay cho T, chúng tôi viết tên của lớp của chúng tôi ví dụ. Sinh viên. CREATOR được sử dụng trong khi UnMarshalling của đối tượng.
Nó có hai phương pháp -
1-T createFromParcel(Parcel parcel) :This method is called when UnMarshalling happen
during receiving the data. Keep care that we receive the data member in same sequence
as we write in writeToPacel(). Here we create a constructor in which we demarshalling
the data.
2-NewArray(int size) : Here we just create an array of given size and return.
public static final Parcelable.Creator<Student> CREATOR = new Parcelable.Creator<Student>() {
@Override
public Student createFromParcel(Parcel source) {
// TODO Auto-generated method stub
return new Student(source);
}
@Override
public Student[] newArray(int size) {
// TODO Auto-generated method stub
return new Student[size];
}
};
để biết thêm: Check Here
Bạn có giải quyết nó? –