Android傳值Intent和Bundle區別

原文: http://tryenough.com/android-intent-bundle


小夥伴問Android傳值Intent和Bundle區別,特此總結下:

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頁面中:

需要先在B頁面中接收數據

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

然後再發數據到C頁面

原文: http://tryenough.com/android-intent-bundle

    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);

原文: http://tryenough.com/android-intent-bundle

在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旨在傳值。

原文: http://tryenough.com/android-intent-bundle

然後看下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代替呢?

  • Bundle內部是由ArrayMap實現的,ArrayMap的內部實現是兩個數組,一個int數組是存儲對象數據對應下標,一個對象數組保存key和value,內部使用二分法對key進行排序,所以在添加、刪除、查找數據的時候,都會使用二分法查找,只適合於小數據量操作,如果在數據量比較大的情況下,那麼它的性能將退化。而HashMap內部則是數組+鏈表結構,所以在數據量較少的時候,HashMap的Entry Array比ArrayMap佔用更多的內存。因爲使用Bundle的場景大多數爲小數據量,我沒見過在兩個Activity之間傳遞10個以上數據的場景,所以相比之下,在這種情況下使用ArrayMap保存數據,在操作速度和內存佔用上都具有優勢,因此使用Bundle來傳遞數據,可以保證更快的速度和更少的內存佔用。
  • 另外一個原因,則是在Android中如果使用Intent來攜帶數據的話,需要數據是基本類型或者是可序列化類型,HashMap使用Serializable進行序列化,而Bundle則是使用Parcelable進行序列化。而在Android平臺中,更推薦使用Parcelable實現序列化,雖然寫法複雜,但是開銷更小,所以爲了更加快速的進行數據的序列化和反序列化,系統封裝了Bundle類,方便我們進行數據的傳輸。

原文: http://tryenough.com/android-intent-bundle

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章