標籤:android bundle intent
不時的回過頭來看看自己的Andriod學習、實踐之路,總發現有些以前不明白的,現在清楚緣由;也會發現一些之前沒怎麼關注的,現在看到了 ,非常想去深刻瞭解的。
比如:Bundle。
在一個Activity的生命週期中,首先要執行的是onCreate方法
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modifyheadphoto);
}
在預設情況下,上面紅色部分 是 onCreate方法的參數 , 預設執行的方法, 都會自動添加,而這部分一般情況,我都不去關注,你呢?
今天,就來搞清楚這個Bundle的作用,以及和Intent的區別。
一、Bundle:A mapping from String values to various Parcelable types
鍵值對的集合
類繼承關係:
java.lang.Object
android.os.Bundle
Bundle類是一個final類:
public final class Bundle extends Objectimplements Parcelable Cloneable
作用:可以用作是兩個Activity間的通訊。
用法:
①、裝載資料:
Bundle mBundle = new Bundle();
mBundle.putString("DataTag", "要傳過去的資料");
Intent intent = new Intent();
intent.setClass(MainActivity.this, Destion.class);
intent.putExtras(mBundle);
②、目標Activity解析資料
Bundle bundle = getIntent().getExtras(); //得到傳過來的bundle
String data = bundle.getString("DataTag");//讀出資料
二、Intent的含義和作用 就略了。。。直接上二者比較:
兩個Activity之間傳遞資料,資料的附加有兩種方式:
一種是直接 intent.putxx();
另一種是 先bundle.putxx(), 然後再調用public Intent putExtras (Bundle extras) 添加bundle.
其實兩種的本質是一樣的。
先看Intent的方法:
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傳值的話最後調用的方法:Intent.putExtras(Bundle extras):
public Intent putExtras(Bundle extras) {
if (mExtras == null) {
mExtras = new Bundle();
}
mExtras.putAll(extras);
return this;
}
可以看到,其實是把之前那個bundle中的資料大量新增到intent內部的bundle中。
其實是和上面的直接用Intent傳鍵值對是一樣的原理。
總之呢,Intent旨在資料傳遞,bundle旨在存取資料,當然intent也提供一部分資料的存取,但比起bundle就顯得不專業,不靈活的多
Android-Bundle認知、和Intent的區別