什么是Bundle?
谷歌官方给出的解释是“A mapping from String keys to various Parcelable
values.”
大概意思就是Bundlle是通过Parcelable来实现序列化的一个key-value对
在安卓源码中,我们也可以看到Bundle是实现了Parcelable接口
public final class Bundle implements Parcelable, Cloneable { ...... }
何为Parcelable?
Parcelable是一种序列化方式,当我们需要用到Intent和Binder传输数据时就需要使用Parcelable,其源码如下
public interface Parcelable {
public static final int PARCELABLE_WRITE_RETURN_VALUE = 0x0001;
public static final int CONTENTS_FILE_DESCRIPTOR = 0x0001;
public int describeContents();
public void writeToParcel(Parcel dest, int flags);
public interface Creator<T> {
public T createFromParcel(Parcel source);
public T[] newArray(int size);
}
}
从源码可以看出来,其实就是一个接口,其各自方法类的功能如下:
describeContents 返回当前对象内容的描述,如果含有文件描述符,返回1,否则返回0,几乎所有情况都返回0
writeToParcel(Parcel out,int flag)将当前对象写入序列化结构中
createFromParcelable(Parcel in) 从序列化后的对象中创建原始对象
newArray(int size)创建指定长度的原始对象数组
我们实际当中是怎么用Bundle呢?
一般都是这样把数据写进Bundle,然后传递出去
Bundle mBundle = new Bundle();
mBundle.putString("mData", "Deazy"); //写进数据
Intent intent = new Intent();
intent.setClass(TestBundle.this, Target.class);
intent.putExtras(mBundle);
而读取过程就是这样
String data = bundle.getString("Data");//读出数据
那么,Bundle源码中是怎么样实现的呢?
我们来看看源码
源码中先定义一个Map<String, Object>类型的mMap
Map<String, Object> mMap = null;
当你写进数据时,就往mMap中添加一个key-value对
public void putString(String key, String value) {
unparcel();
mMap.put(key, value);
}
获得数据也很容易,也就是往mMap中读取数据
public String getString(String key) {
unparcel();
Object o = mMap.get(key);
if (o == null) {
return null;
}
try {
return (String) o;
} catch (ClassCastException e) {
typeWarning(key, o, "String", e);
return null;
}
}
总结:Bundle其实也不难,就是IPC通信之间的一个Parcelable,存储跟读取数据都在Bundle内部类中的Map<String, Object>类型mMap中
如果想了解更多可以参看一下源码,基本思路是这样,如果有哪些地方不对,有望大神指出