一、Parcel概述
在Android中,應用程序默認是運行在自己的進程中,但有時候需要與其他進程進行通信,這時候就需要利用Android提供的進程間通信(IPC)機制。在Android中,進程間通信有多種方式,其中最常用的一種是使用Binder機制。但是,使用Binder機制比較麻煩,需要繼承自IBinder類,像AIDL這樣的語言還需要寫一些介面描述文件,學習和使用起來比較困難。
而Parcel則是Android中比較簡單的一種進程間通信方式,它同樣也是在Android內部使用的。Parcel可以用來在多個進程之間傳遞數據,使用起來非常方便。
二、Parcel的使用
1、Parcel類
Parcel類是Android提供的一個工具類,用於在進程之間傳遞數據。在使用Parcel類之前,需要先將需要傳遞的數據寫入Parcel中,然後在另一個進程中將數據從Parcel中讀取出來。使用Parcel類需要注意以下幾點:
1)Parcel類封裝了一個byte數組,使用writeXXX()方法向其中寫入數據,使用readXXX()方法從中讀取數據,讀寫數據的順序應該保持一致;
2)Parcel中的數據是按值傳遞的,也就是說傳遞的是數據的副本而不是數據本身;
3)Parcel中並沒有提供序列化和反序列化的功能,需要使用者自己實現。
2、將數據寫入Parcel中
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(name);
dest.writeFloat(price);
}
在這個例子中,我們向Parcel類中寫入了一個整型的id、一個字元串的name和一個浮點型的price。
3、從Parcel中讀取數據
public Book(Parcel source) {
id = source.readInt();
name = source.readString();
price = source.readFloat();
}
在這個例子中,我們從Parcel類中讀取了一個整型的id、一個字元串的name和一個浮點型的price。
三、案例講解
我們假設有兩個應用程序,一個叫做App1,另一個叫做App2。我們需要在這兩個應用程序之間傳遞數據,具體操作如下:
1、定義一個數據類Book,並通過實現Parcelable介面來實現序列化和反序列化:
public class Book implements Parcelable {
private int id;
private String name;
private float price;
public Book(int id, String name, float price) {
this.id = id;
this.name = name;
this.price = price;
}
protected Book(Parcel in) {
id = in.readInt();
name = in.readString();
price = in.readFloat();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(name);
dest.writeFloat(price);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator CREATOR = new Creator() {
@Override
public Book createFromParcel(Parcel in) {
return new Book(in);
}
@Override
public Book[] newArray(int size) {
return new Book[size];
}
};
public int getId() {
return id;
}
public String getName() {
return name;
}
public float getPrice() {
return price;
}
}
2、在App1中,創建一個數據類的對象,並將其寫入一個Intent中:
Book book = new Book(1, "Android", 100.00f);
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example.app2", "com.example.app2.BookActivity"));
intent.putExtra("book", book);
startActivity(intent);
在這裡,我們將數據類Book的對象book寫入Intent中,並指定了接收方的packageName和類名,啟動了App2中的BookActivity。
3、在App2中的BookActivity中,讀取傳遞過來的數據:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
Book book = getIntent().getParcelableExtra("book");
if (book != null) {
TextView textView = findViewById(R.id.textView);
textView.setText("Id: " + book.getId() + "\nName: " + book.getName() + "\nPrice:" + book.getPrice());
}
}
在這裡,我們通過getParcelableExtra()方法從Intent中獲取了數據類Book的對象book,然後將其顯示到了界面上。
四、小結
在Android的開發過程中,進程間通信是一個非常重要的話題。Parcel是Android內部使用的輕量級進程間通信方式,雖然比起Binder機制來說它的功能較為簡單,但是它的使用非常方便,是開發中經常使用的一種方式。
注意,上述代碼僅供參考,實際開發中需要根據具體情況進行調整。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/182182.html