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的差別