這幾天在寫android小程式的時候碰到了bundle,突然發現還不清楚intent和bundle之間的關系,決定百度google之。後來發現很多都在說用法,沒提到什麼本質差別的,是以去翻源碼- -
首先來看下intent:
public Intent putExtra(String name, boolean value);
public Intent putExtra(String name, byte value);
public Intent putExtra(String name, char value);
public Intent putExtra(String name, short value);
public Intent putExtra(String name, int value);
public Intent putExtra(String name, long value);
public Intent putExtra(String name, float value);
public Intent putExtra(String name, double value);
public Intent putExtra(String name, String value);
public Intent putExtra(String name, CharSequence value);
public Intent putExtra(String name, Parcelable value);
public Intent putExtra(String name, Parcelable[] value);
...
intent内部定義了很多put方法,功能都是把key-val存進來。我們來看一個具體put函數的内部實作:
public Intent putExtra(String name, boolean value) {
if (mExtras == null) {
mExtras = new Bundle();
}
mExtras.putBoolean(name, value);
return this;
}
其中mExtras是intent内部定義的一個private Bundle變量。
大家可以看到,intent其實是調用了bundle相應的put函數,也就是說,intent内部還是用bundle來實作資料傳遞的,隻是封裝了一層而已。
再來說Bundle:
public void putBoolean(String key, boolean value);
public void putByte(String key, byte value);
public void putChar(String key, char value);
...
put函數都是分類型的。
再來看用法:
隻用intent:類型什麼的是不需要你來操心的,你隻需要putExtra就好了,内部會都存在一個bundle對象中。key-val對是一個一個被加進去的。
用intent和bundle:key-val對先被一個個的加到bundle裡面,再把這個bundle put到intent中,其中用了下面這個函數:
public Intent putExtras(Bundle extras) {
if (mExtras == null) {
mExtras = new Bundle();
}
mExtras.putAll(extras);
return this;
}
可以看到,其實是把之前那個bundle中的資料批量添加到intent内部的bundle中。
取資料的時候,可以一個個的取出來(這個不贅述了),也可以把資料打包一起取出來:
public Bundle getExtras() {
return (mExtras != null)
? new Bundle(mExtras)
: null;
}
這個函數是把目前intent中所有的資料一起打包的(假如說你既用了bundle也用了intent本身的put函數來加資料,最後用get函數傳回的是bundle+其他資料一起的)。
說到底呢,差別是什麼,如果你想對資料進行比較靈活的操作(批量操作什麼的)的話就用bundle吧,當然你也可以getIntent之後直接添加資料然後把這個intent發送出去(當然這是不推薦的一種用法啦= =)。
還有就是,Bundle是可以對對象進行操作的,而Intent不可以。Bundle相對于Intent比較偏下層,比Intent接口更多,更靈活,但Bundle仍需要借助Intent才能在Activity之間傳遞。
概括一下,Intent旨在資料傳遞,bundle旨在存取資料,當然intent也提供一部分資料的存取,但比起bundle就顯得不專業,不靈活的多。