前言
Bundle 翻譯成中文的意思是“捆綁”,常用在Activity間傳遞參數(shù),之前一開始并不太待見,原因是Intent本身就可以傳遞,Intent.putExtra("key", value),為何還要用Bundle呢?
正巧小伙伴問Android傳值Intent和Bundle區(qū)別,特此總結(jié)下:
Intent與Bundle在傳值上的區(qū)別
首先從使用上:
Intent方式:
假設(shè)需要將數(shù)據(jù)從頁面A傳遞到B,然后再傳遞到C。
A頁面中:
Intent intent=new Intent(MainActivity.this,BActivity.class);
intent.putExtra("String","MainActivity中的值");
intent.putExtra("int",11);
startActivity(intent);
B頁面中:
需要先在B頁面中接收數(shù)據(jù)
Intent intent = getIntent();
string = intent.getStringExtra("String");
key = intent.getIntExtra("int",0);
然后再發(fā)數(shù)據(jù)到C頁面
Intent intent=new Intent(BActivity.this,CActivity.class);
intent.putExtra("String1",string);
intent.putExtra("int1",key);
intent.putExtra("boolean",true);
startActivity(intent);
可以看到,使用的時(shí)候不方便的地方是需要在B頁面將數(shù)據(jù)一條條取出來然后再一條條傳輸給C頁面。
而使用Bundle的話,在B頁面可以直接取出傳輸?shù)腂undle對(duì)象然后傳輸給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頁面接收數(shù)據(jù):
Intent intent = getIntent();
bundle=intent.getBundleExtra("bundle");
然后在B頁面中發(fā)送數(shù)據(jù):
Intent intent=new Intent(BActivity.this,CActivity.class);
//可以傳給CActivity額外的值
bundle.putBoolean("boolean",true);
intent.putExtra("bundle1",bundle);
startActivity(intent);
總結(jié):
Bundle可對(duì)對(duì)象進(jìn)行操作,而Intent是不可以。Bundle相對(duì)于Intent擁有更多的接口,用起來比較靈活,但是使用Bundle也還是需要借助Intent才可以完成數(shù)據(jù)傳遞總之,Bundle旨在存儲(chǔ)數(shù)據(jù),而Intent旨在傳值。
然后看下intent的put方法源碼:
public @NonNull Intent putExtra(String name, Parcelable value) {
if (mExtras == null) {
mExtras = new Bundle();
}
mExtras.putParcelable(name, value);
return this;
}
可以看到其實(shí)內(nèi)部也是使用的Bundle來傳輸?shù)臄?shù)據(jù)。
題外話
為什么Bundle不直接使用Hashmap代替呢?
Bundle內(nèi)部是由ArrayMap實(shí)現(xiàn)的,ArrayMap的內(nèi)部實(shí)現(xiàn)是兩個(gè)數(shù)組,一個(gè)int數(shù)組是存儲(chǔ)對(duì)象數(shù)據(jù)對(duì)應(yīng)下標(biāo),一個(gè)對(duì)象數(shù)組保存key和value,內(nèi)部使用二分法對(duì)key進(jìn)行排序,所以在添加、刪除、查找數(shù)據(jù)的時(shí)候,都會(huì)使用二分法查找,只適合于小數(shù)據(jù)量操作,如果在數(shù)據(jù)量比較大的情況下,那么它的性能將退化。而HashMap內(nèi)部則是數(shù)組+鏈表結(jié)構(gòu),所以在數(shù)據(jù)量較少的時(shí)候,HashMap的Entry Array比ArrayMap占用更多的內(nèi)存。因?yàn)槭褂肂undle的場(chǎng)景大多數(shù)為小數(shù)據(jù)量,我沒見過在兩個(gè)Activity之間傳遞10個(gè)以上數(shù)據(jù)的場(chǎng)景,所以相比之下,在這種情況下使用ArrayMap保存數(shù)據(jù),在操作速度和內(nèi)存占用上都具有優(yōu)勢(shì),因此使用Bundle來傳遞數(shù)據(jù),可以保證更快的速度和更少的內(nèi)存占用。
另外一個(gè)原因,則是在Android中如果使用Intent來攜帶數(shù)據(jù)的話,需要數(shù)據(jù)是基本類型或者是可序列化類型,HashMap使用Serializable進(jìn)行序列化,而Bundle則是使用Parcelable進(jìn)行序列化。而在Android平臺(tái)中,更推薦使用Parcelable實(shí)現(xiàn)序列化,雖然寫法復(fù)雜,但是開銷更小,所以為了更加快速的進(jìn)行數(shù)據(jù)的序列化和反序列化,系統(tǒng)封裝了Bundle類,方便我們進(jìn)行數(shù)據(jù)的傳輸。
好了,以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)html5模板網(wǎng)的支持。