探讨Android源码中Bundle

什么是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中

如果想了解更多可以参看一下源码,基本思路是这样,如果有哪些地方不对,有望大神指出

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sun cat

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值