小伙伴问Android传值Intent和Bundle区别,特此总结下:java
首先从使用上:android
Intent方式:数组
假设须要将数据从页面A传递到B,而后再传递到C。性能
A页面中:this
Intent intent=new Intent(MainActivity.this,BActivity.class); intent.putExtra("String","MainActivity中的值"); intent.putExtra("int",11); startActivity(intent);
B页面中:code
须要先在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);
能够看到,使用的时候不方便的地方是须要在B页面将数据一条条取出来而后再一条条传输给C页面。接口
而使用Bundle的话,在B页面能够直接取出传输的Bundle对象而后传输给C页面。内存
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代替呢?
另一个缘由,则是在Android中若是使用Intent来携带数据的话,须要数据是基本类型或者是可序列化类型,HashMap使用Serializable进行序列化,而Bundle则是使用Parcelable进行序列化。而在Android平台中,更推荐使用Parcelable实现序列化,虽然写法复杂,可是开销更小,因此为了更加快速的进行数据的序列化和反序列化,系统封装了Bundle类,方便咱们进行数据的传输。