fred-ye / summary

my blog
43 stars 9 forks source link

[Android] Android中Parcelable的使用 #45

Open fred-ye opened 9 years ago

fred-ye commented 9 years ago

之所以采用Parcelable是因为在两个Activity之间传递对象,采用Parcelable会比Serializable的效率要高。因为Serializable序列化采用大量反射,且会产生很多临时变量,从而引起频繁的GC。Parcelable不能使用在要将数据存储在磁盘上的情况,因为Parcelable在外界有变化的情况下不能很好的保证数据的持续性。

定义实体

package com.example.test.entity;

import android.os.Parcel;
import android.os.Parcelable;

public class Book implements Parcelable {
    private String name;
    private String author;

    public Book() {

    }

    public Book(String name, String author) {
        this.name = name;
        this.author = author;
    }
    public String getName() {
        return this.name;
    }
    public String getAuthor() {
        return this.author;
    }

    @Override
    public int describeContents() {
        return 0;
    }
    //通过writeToParcel将你的对象映射成Parcel对象
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeString(author);
    }

    public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() {
        //通过createFromParcel将Parcel对象映射成需要的对象
        @Override
        public Book createFromParcel(Parcel source) {
            // TODO Auto-generated method stub
            return new Book(source);
        }

        @Override
        public Book[] newArray(int size) {
            return null;
        }

    };
    //在从Parcelable中取值会调用这个方法,方法中提取属性的顺序必须是要和writeToParcel中一致。
    public Book(Parcel in) {
        name = in.readString();
        author = in.readString();
    }
}

调用方式,如在第一个Activity中

Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("book", new Book("book_name", "author"));
startActivity(intent);

在第二个Activity中

Intent intent = getIntent();
Book book = intent.getParcelableExtra("book");
Log.i("Second", book.getAuthor() + "   " + book.getName());