Android-Bundle認知、和Intent的差別

來源:互聯網
上載者:User

標籤:data   資料   ext   繼承   rri   create   return   部分   也會   

不時的回過頭來看看自己的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的差別

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.