Android中Parcelable的使用

1、封装要进行跨进程传输的对象

package com.lewa; import android.graphics.Bitmap; import android.os.Parcel; import android.os.Parcelable; public class WeiBoWidget implements Parcelable{ private String contentText; private Bitmap contentPicture; public WeiBoWidget(){} public String getContentText() { return contentText; } public void setContentText(String contentText) { this.contentText = contentText; } public Bitmap getContentPicture() { return contentPicture; } public void setContentPicture(Bitmap contentPicture) { this.contentPicture = contentPicture; } @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(contentText); if(this.contentPicture != null){ dest.writeInt(1); this.contentPicture.writeToParcel(dest, flags); }else{ dest.writeInt(0); } } public static final Parcelable.Creator<WeiBoWidget> CREATOR = new Parcelable.Creator<WeiBoWidget>() { @Override public WeiBoWidget createFromParcel(Parcel source) { // TODO Auto-generated method stub WeiBoWidget weiBoWidget = new WeiBoWidget(); weiBoWidget.contentText = source.readString(); if(0 != source.readInt()){ weiBoWidget.contentPicture = Bitmap.CREATOR.createFromParcel(source);//因为Bitmap实现了Parcelable接口,所以这里可以这样使用 } return weiBoWidget; } @Override public WeiBoWidget[] newArray(int size) { // TODO Auto-generated method stub return new WeiBoWidget[size]; } }; }

2、使用Intent、Bundle进行传输

Intent intent = new Intent(); intent.setAction(GET_DATA_OVER); Bundle extra = new Bundle(); extra.putParcelableArrayList("weiBoWidgets", (ArrayList<WeiBoWidget>) result); intent.putExtras(extra); context.sendBroadcast(intent);

你可能感兴趣的:(Android中Parcelable的使用)