Android传值Intent和Bundle的区别

Intent的使用

假设需要将数据从页面A传递到B,然后再传递到C。
A页面:

	Intent intent=new Intent(MainActivity.this,BActivity.class);
    intent.putExtra("String","MainActivity中的值");
    intent.putExtra("int",11);
    startActivity(intent);

B页面中:

	Intent intent = getIntent();
    string = intent.getStringExtra("String");
    key = intent.getIntExtra("int",0);

然后再发数据到C页面:

    Intent intent=new Intent(BActivity.this,CActivity.class);
    intent.putExtra("String1",string);
    intent.putExtra("int1",key);
    intent.putExtra("boolean",true);
    startActivity(intent);

Bundle使用方式

A页面中:

    Intent intent = new Intent(MainActivity.this, BActivity.class);
    Bundle bundle = new Bundle();
    bundle.putString("String","MainActivity中的值");
    bundle.putInt("int",11);
    intent.putExtra("bundle",bundle);
    startActivity(intent);

在B页面接收数据:

Intent intent = getIntent();
bundle=intent.getBundleExtra("bundle");

然后在B页面中发送数据:

    Intent intent=new Intent(BActivity.this,CActivity.class);
    //可以传给CActivity额外的值
    bundle.putBoolean("boolean",true);
    intent.putExtra("bundle1",bundle);
    startActivity(intent);

总结

Bundle可对对象进行操作,而Intent是不可以。Bundle相对于Intent拥有更多的接口,用起来比较灵活,但是使用Bundle也还是需要借助Intent才可以完成数据传递总之,Bundle旨在存储数据,而Intent旨在传值。

然后看下intent的put方法源码:
public @NonNull Intent putExtra(String name, Parcelable value) { if (mExtras == null) { mExtras = new Bundle(); } mExtras.putParcelable(name, value); return this; }
可以看到其实内部也是使用的Bundle来传输的数据。

为什么Bundle不直接使用Hashmap代替呢

1、Bundle内部是由ArrayMap实现的,ArrayMap的内部实现是两个数组,一个int数组是存储对象数据对应下标,一个对象数组保存key和value,内部使用二分法对key进行排序,所以在添加、删除、查找数据的时候,都会使用二分法查找,只适合于小数据量操作,如果在数据量比较大的情况下,那么它的性能将退化。而HashMap内部则是数组+链表结构,所以在数据量较少的时候,HashMap的Entry Array比ArrayMap占用更多的内存。因为使用Bundle的场景大多数为小数据量,我没见过在两个Activity之间传递10个以上数据的场景,所以相比之下,在这种情况下使用ArrayMap保存数据,在操作速度和内存占用上都具有优势,因此使用Bundle来传递数据,可以保证更快的速度和更少的内存占用。
2、另外一个原因,则是在Android中如果使用Intent来携带数据的话,需要数据是基本类型或者是可序列化类型,HashMap使用Serializable进行序列化,而Bundle则是使用Parcelable进行序列化。而在Android平台中,更推荐使用Parcelable实现序列化,虽然写法复杂,但是开销更小,所以为了更加快速的进行数据的序列化和反序列化,系统封装了Bundle类,方便我们进行数据的传输。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值