編輯:關於 Android 程式設計
要在 Activity 之間傳遞一個自定義的複雜對象,Parcelable 是標准答案。本文用一個「漫畫角色」的例子把整個流程走一遍。
Intent 的 putExtra 只接受基本類型和實現了 Parcelable 或 Serializable 的對象。相比 Java 原生的 Serializable,Parcelable 由 Google 專為內存環境設計,序列化過程不涉及反射與臨時字節流的創建,性能明顯更好,是跨進程/跨 Activity 傳遞對象的首選。
package com.example.sendobjfromactivity.bean;
import android.graphics.Bitmap;
public class Cartoon {
private Bitmap figure;
private String name;
private String creator;
public Bitmap getFigure() { return figure; }
public void setFigure(Bitmap figure) { this.figure = figure; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getCreator() { return creator; }
public void setCreator(String creator) { this.creator = creator; }
}
接口要求實現三個部分:writeToParcel 負責序列化(把對象寫進 Parcel 容器),CREATOR 負責反序列化(從 Parcel 讀出並構造實例),describeContents 通常返回 0。
package com.example.sendobjfromactivity.bean;
import android.graphics.Bitmap;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
public class ParcelableCartoon implements Parcelable {
private Cartoon cartoon;
private static final String MSG = "MESSAGE";
public ParcelableCartoon(Cartoon cartoon) {
Log.i(MSG, "ParcelableCartoon::ParcelableCartoon@Cartoon");
this.cartoon = cartoon;
}
/**
* Flatten this object in to a Parcel.
*
* @param dest The Parcel in which the object should be written.
* @param flags Additional flags about how the object should be written.
* May be 0 or {@link #PARCELABLE_WRITE_RETURN_VALUE}.
*/
@Override
public void writeToParcel(Parcel dest, int flags) {
Log.i(MSG, "ParcelableCartoon::writeToParcel");
dest.writeString(cartoon.getName());
dest.writeString(cartoon.getCreator());
dest.writeParcelable(cartoon.getFigure(), PARCELABLE_WRITE_RETURN_VALUE);
}
/**
* 完成對序列化對象的反序列化
*/
public static final Parcelable.Creator<ParcelableCartoon> CREATOR =
new Parcelable.Creator<ParcelableCartoon>()() {
/**
* Create a new instance of the Parcelable class, instantiating it
* from the given Parcel whose data had previously been written by
* {@link Parcelable#writeToParcel Parcelable.writeToParcel()}.
*/
@Override
public ParcelableCartoon createFromParcel(Parcel source) {
Log.i(MSG, "ParcelableCartoon::Parcelable.Creator::createFromParcel");
return new ParcelableCartoon(source);
}
@Override
public ParcelableCartoon[] newArray(int size) {
Log.i(MSG, "ParcelableCartoon::Parcelable.Creator::newArray");
return new ParcelableCartoon[size];
}
};
public ParcelableCartoon(Parcel in) {
Log.i(MSG, "ParcelableCartoon::ParcelableCartoon@Parcel");
cartoon = new Cartoon();
cartoon.setName(in.readString());
cartoon.setCreator(in.readString());
cartoon.setFigure((Bitmap) in.readParcelable(Bitmap.class.getClassLoader()));
}
public Cartoon getCartoon() {
Log.i(MSG, "ParcelableCartoon::getCartoon");
return cartoon;
}
@Override
public int describeContents() {
Log.i(MSG, "ParcelableCartoon::describeContents");
return 0;
}
}
這裡有個至關重要的細節:writeToParcel 中的寫入順序,必須與 Parcel in 構造函數中的讀取順序完全一致。順序錯位不會報錯,只會讀出莫名其妙的數據或拋 BadParcelableException,排查起來很費勁。
package com.example.sendobjfromactivity;
import java.io.InputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.example.sendobjfromactivity.bean.Cartoon;
import com.example.sendobjfromactivity.bean.ParcelableCartoon;
public class SendObjFromActivity extends Activity {
private Button sendData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sendData = (Button) this.findViewById(R.id.button1);
sendData.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Cartoon cartoon = new Cartoon();
cartoon.setName("Android");
cartoon.setCreator("Google");
InputStream is = getResources().openRawResource(R.drawable.ic_launcher);
Bitmap bitmap = BitmapFactory.decodeStream(is);
cartoon.setFigure(bitmap);
Intent intent = new Intent(SendObjFromActivity.this, ReceiveObjActivity.class);
// 完成對象的序列化操作
ParcelableCartoon parcelableCartoon = new ParcelableCartoon(cartoon);
intent.putExtra("msg", parcelableCartoon);
startActivity(intent);
}
});
}
}
package com.example.sendobjfromactivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.sendobjfromactivity.bean.Cartoon;
import com.example.sendobjfromactivity.bean.ParcelableCartoon;
public class ReceiveObjActivity extends Activity {
private ImageView showImage;
private TextView showText;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("MESSAGE", "進入到了另外的一個 activity 中去");
super.onCreate(savedInstanceState);
setContentView(R.layout.display_obj);
showImage = (ImageView) this.findViewById(R.id.imageView1);
showText = (TextView) this.findViewById(R.id.textView1);
Intent intent = getIntent();
ParcelableCartoon parcelableCartoon = (ParcelableCartoon) intent.getParcelableExtra("msg");
Cartoon cartoon = parcelableCartoon.getCartoon();
showImage.setImageBitmap(cartoon.getFigure());
showText.setText(cartoon.getName() + "\n" + cartoon.getCreator());
}
}
在接收側,框架會調用 CREATOR.createFromParcel() 完成反序列化,這也正是為什麼 CREATOR 必須是 public static final 的——框架通過反射訪問它。
佈局文件 main.xml 與 display_obj.xml 比較簡單,這裡不再贅述。
幾個實務建議:
@Parcelize 註解即可,代碼量能減少一個數量級。TransactionTooLargeException。傳圖片應該傳路徑或 URI,而不是傳 Bitmap 本身。
Android 4.0 撥號啟動流程剖析(三):PhoneApp 與 Framework 層的通訊
Android 幾乎所有原始碼都公開,要分析 Framework 就先把碼拿到手。我在 Ubuntu 14.04 上搭好環境並下載 Android 4.0 原始碼(含 F
安卓手機防中毒指南 四招遠離惡意流氓軟件
智能手機越來越深入生活,伴隨而來的隱患也層出不窮。其中讓人最頭疼的,莫過於惡意流氓軟件與手機病毒。究竟該如何守住自己的手機?小編整理了四個實用的自保技巧。 一、挑一個靠
Android 開發必讀:程序員一定要懂的重要設計理念
日前帶著自己的作品參加服務外包大賽,因抽籤順位較後而等待许久,便與前排參賽者聊起 Android 開發經驗,彼此展示作品。有朋友建議我參考官方 Design 的設計原則,
安卓開發之 ViewDragHelper 使用大全,並自定義可下拉展開內容的 ViewGroup
一、ViewDragHelper 一個自定義 ViewGroup 的工具類,它提供了許多有用的方法和狀態,允許用戶去拖拽並繪製子 View 在自定義 ViewGroup