小夥伴問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類,方便咱們進行數據的傳輸。