Android Bundle詳解

1 Bundle介紹

Bundle主要用於傳遞數據;它保存的數據,是以key-value(鍵值對)的形式存在的。html

 

咱們常常使用Bundle在Activity之間傳遞數據,傳遞的數據能夠是boolean、byte、int、long、float、double、string等基本類型或它們對應的數組,也能夠是對象或對象數組。當Bundle傳遞的是對象或對象數組時,必須實現Serializable 或Parcelable接口。下面分別介紹Activity之間如何傳遞基本類型、傳遞對象。java

 

2傳遞基本類型

Bundle提供了各類經常使用類型的putXxx()/getXxx()方法,用於讀寫基本類型的數據。Bundle操做基本數據類型的API表格以下所示:android

 

寫數據的方法以下:數組

[java] view plain copy print?在CODE上查看代碼片派生到個人代碼片app

  1. // "com.test" is the package name of the destination class  ide

  2. // "com.test.Activity02" is the full class path of the destination class  函數

  3. Intent intent = new Intent().setClassName("com.bundletest""com.bundletest.Bundle02");  this

  4.   

  5. Bundle bundle = new Bundle();  spa

  6. bundle.putString("name""skywang");  .net

  7. bundle.putInt("height"175);  

  8. intent.putExtras(bundle);  

  9.   

  10. startActivity(intent);  

  11.   

  12. // end current class  

  13. finish();  


對應的讀數據的方法以下:

[java] view plain copy print?在CODE上查看代碼片派生到個人代碼片

  1. Bundle bundle = this.getIntent().getExtras();    

  2.     

  3. String name = bundle.getString("name");    

  4. int height = bundle.getInt("height");  



3傳遞Parcelable類型的對象

3.1 Parcelable說明

Parcelable是Android自定義的一個接口,它包括了將數據寫入Parcel和從Parcel中讀出的API。一個實體(用類來表示),若是須要封裝到bundle消息中去,能夠經過實現Parcelable接口來實現。


Parcelable和Serializable的API以下表:



3.2 Parcelable接口說明

[java] view plain copy print?在CODE上查看代碼片派生到個人代碼片

  1. public interface Parcelable {  

  2.     //內容描述接口,基本不用管  

  3.     public int describeContents();  

  4.     //寫入接口函數,打包  

  5.     public void writeToParcel(Parcel dest, int flags);  

  6.     //讀取接口,目的是要從Parcel中構造一個實現了Parcelable的類的實例處理。由於實現類在這裏仍是不可知的,因此須要用到模板的方式,繼承類名經過模板參數傳入。  

  7.     //爲了可以實現模板參數的傳入,這裏定義Creator嵌入接口,內含兩個接口函數分別返回單個和多個繼承類實例。  

  8.     public interface Creator<T> {  

  9.         public T createFromParcel(Parcel source);  

  10.         public T[] newArray(int size);  

  11.  }  

  12. }  



3.3 Parcelable接口的實現方法

從parcelable接口定義中,咱們能夠看到,實現parcelable接口,須要咱們實現下面幾個方法:
(01)describeContents方法。內容接口描述,默認返回0就能夠;
(02)writeToParcel 方法。該方法將類的數據寫入外部提供的Parcel中.即打包須要傳遞的數據到Parcel容器保存,以便從parcel容器獲取數據,該方法聲明以下:
writeToParcel(Parcel dest, int flags) 具體參數含義見doc文檔
(3.)靜態的Parcelable.Creator接口,本接口有兩個方法:
createFromParcel(Parcelin)  從Parcel容器中讀取傳遞數據值,封裝成Parcelable對象返回邏輯層。
newArray(int size) 建立一個類型爲T,長度爲size的數組,僅一句話(returnnew T[size])便可。方法是供外部類反序列化本類數組使用。

 

4傳遞Serializable類型的對象

4.1 Serializable說明

Serializable是一個對象序列化的接口。一個類只有實現了Serializable接口,它的對象纔是可序列化的。所以若是要序列化某些類的對象,這些類就必須實現Serializable接口。而實際上,Serializable是一個空接口,沒有什麼具體內容,它的目的只是簡單的標識一個類的對象能夠被序列化。

4.2 Serializable接口的實現方法

很簡單,只要implements Serializable接口就能夠了

 

5 demo演示程序

下面是對實現上述三種數據傳遞方式的BundleTest(demo程序)進行簡要介紹

5.1 demo概要

BundleTest共包含了4個java文件和2個layout文件(main.xml和main2.xml)

Bundle01.java     —— 默認的主Activity窗口。

Bundle02.java     —— 主Activity用於跳轉的目的窗口。

Book.java            —— 實現Parcelable接口的類

Person.java        —— 實現Serializable接口的類

main.xml             —— Bundle01.java的layout文件

main2.xml           —— Bundle02.java的layout文件

 

工程文件結構以下所示:


 

5.2代碼

AndroidManifest.xml

[html] view plain copy print?在CODE上查看代碼片派生到個人代碼片

  1. <?xml version="1.0" encoding="utf-8"?>  

  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  

  3.       package="com.bundletest"  

  4.       android:versionCode="1"  

  5.       android:versionName="1.0">  

  6.       

  7.     <application android:icon="@drawable/icon" android:label="@string/app_name">  

  8.         <activity android:name=".Bundle01"  

  9.                   android:label="@string/app_name">  

  10.             <intent-filter>  

  11.                 <action android:name="android.intent.action.MAIN" />  

  12.                 <category android:name="android.intent.category.LAUNCHER" />  

  13.             </intent-filter>  

  14.         </activity>  

  15.         <activity android:name=".Bundle02"> </activity>  

  16.     </application>  

  17.     <uses-sdk android:minSdkVersion="11" />  

  18. </manifest>   




main.xml

[html] view plain copy print?在CODE上查看代碼片派生到個人代碼片

  1. <?xml version="1.0" encoding="utf-8"?>  

  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  

  3.     android:orientation="vertical"  

  4.     android:layout_width="fill_parent"  

  5.     android:layout_height="fill_parent"  

  6.     >  

  7.     <TextView    

  8.         android:layout_width="fill_parent"   

  9.         android:layout_height="wrap_content"   

  10.         android:text="@string/app_01"  

  11.         />  

  12.   

  13.     <Button    

  14.         android:id="@+id/btnBasic"   

  15.         android:layout_width="fill_parent"   

  16.         android:layout_height="wrap_content"   

  17.         android:text="@string/text_basic"  

  18.         />  

  19.   

  20.     <Button    

  21.         android:id="@+id/btnPar"   

  22.         android:layout_width="fill_parent"   

  23.         android:layout_height="wrap_content"   

  24.         android:text="@string/text_par"  

  25.         />  

  26.   

  27.     <Button    

  28.         android:id="@+id/btnSer"   

  29.         android:layout_width="fill_parent"   

  30.         android:layout_height="wrap_content"   

  31.         android:text="@string/text_ser"  

  32.         />  

  33.   

  34.   

  35.   

  36. </LinearLayout>  




main2.xml

[html] view plain copy print?在CODE上查看代碼片派生到個人代碼片

  1. <?xml version="1.0" encoding="utf-8"?>  

  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  

  3.     android:orientation="vertical"  

  4.     android:layout_width="fill_parent"  

  5.     android:layout_height="fill_parent"  

  6.     >  

  7.     <TextView    

  8.         android:layout_width="fill_parent"   

  9.         android:layout_height="wrap_content"   

  10.         android:text="@string/app_02"  

  11.         />  

  12.   

  13.     <Button    

  14.         android:id="@+id/btnBack"   

  15.         android:layout_width="fill_parent"   

  16.         android:layout_height="wrap_content"   

  17.         android:text="@string/text_jump_back"  

  18.         />  

  19.       

  20. </LinearLayout>  




strings.xml

[html] view plain copy print?在CODE上查看代碼片派生到個人代碼片

  1. <?xml version="1.0" encoding="utf-8"?>  

  2. <resources>  

  3.     <string name="hello">Hello MyBundleTest!</string>  

  4.     <string name="app_name">MyBundleTest</string>  

  5.     <string name="app_01">Bundle_01</string>  

  6.     <string name="app_02">Bundle_02</string>  

  7.     <string name="text_basic">Bundle Basic Data</string>  

  8.     <string name="text_par">Bundle Parcelable Data</string>  

  9.     <string name="text_ser">Bundle Seriable Data</string>  

  10.     <string name="text_jump_back">Jump Back to Bundler01</string>  

  11. </resources>  




Bundle01.java

[java] view plain copy print?在CODE上查看代碼片派生到個人代碼片

  1. package com.bundletest;  

  2.   

  3. import android.app.Activity;  

  4. import android.os.Bundle;    

  5. import android.view.View;  

  6. import android.view.View.OnClickListener;  

  7. import android.widget.Button;  

  8. import android.content.Intent;  

  9. import android.util.Log;  

  10.   

  11. public class Bundle01 extends Activity implements View.OnClickListener{  

  12.   

  13.     private static final String TAG = "skywang-->Bundle01";  

  14.   

  15.     private Button mBtnBasic = null;  

  16.     private Button mBtnPar = null;  

  17.     private Button mBtnSer = null;  

  18.   

  19.     @Override  

  20.     public void onCreate(Bundle savedInstanceState) {  

  21.         super.onCreate(savedInstanceState);  

  22.         setContentView(R.layout.main);  

  23.   

  24.         mBtnBasic = (Button) findViewById(R.id.btnBasic);  

  25.         mBtnBasic.setOnClickListener(this);  

  26.   

  27.         mBtnPar = (Button) findViewById(R.id.btnPar);  

  28.         mBtnPar.setOnClickListener(this);  

  29.   

  30.         mBtnSer = (Button) findViewById(R.id.btnSer);  

  31.         mBtnSer.setOnClickListener(this);  

  32.     }  

  33.   

  34.   

  35.     @Override  

  36.     public void onClick(View view) {  

  37.         switch (view.getId()) {  

  38.             case R.id.btnBasic:  

  39.                 sendBasicDataThroughBundle();  

  40.                 break;  

  41.             case R.id.btnPar:  

  42.                 sendParcelableDataThroughBundle();  

  43.                 break;  

  44.             case R.id.btnSer:  

  45.                 sendSeriableDataThroughBundle();  

  46.                 break;  

  47.             default:  

  48.                 break;  

  49.   

  50.         }  

  51.     }  

  52.   

  53.     // sent basic data, such as int, strin, etc...  through bundle  

  54.     private void sendBasicDataThroughBundle(){    

  55.         // "com.test" is the package name of the destination class  

  56.         // "com.test.Activity02" is the full class path of the destination class  

  57.         Intent intent = new Intent().setClassName("com.bundletest""com.bundletest.Bundle02");  

  58.           

  59.         Bundle bundle = new Bundle();  

  60.         bundle.putString("name""skywang");  

  61.         bundle.putInt("height"175);  

  62.         intent.putExtras(bundle);  

  63.           

  64.         startActivity(intent);  

  65.   

  66.         // end current class  

  67.         finish();  

  68.     }  

  69.   

  70.     // sent object through Pacelable  

  71.     private void sendParcelableDataThroughBundle(){    

  72.         Intent intent = new Intent().setClassName("com.bundletest""com.bundletest.Bundle02");  

  73.   

  74.         Book mBook = new Book();  

  75.         mBook.setBookName("Android");  

  76.         mBook.setAuthor("skywang");  

  77.         mBook.setPublishTime(2013);  

  78.   

  79.         Bundle mBundle = new Bundle();  

  80.         mBundle.putParcelable("ParcelableValue", mBook);  

  81.         intent.putExtras(mBundle);  

  82.             

  83.         startActivity(intent);  

  84.         finish();  

  85.     }  

  86.   

  87.     // sent object through seriable  

  88.     private void sendSeriableDataThroughBundle(){    

  89.         Intent intent = new Intent().setClassName("com.bundletest""com.bundletest.Bundle02");  

  90.   

  91.         Person mPerson = new Person();  

  92.         mPerson.setName("skywang");  

  93.         mPerson.setAge(24);  

  94.   

  95.         Bundle mBundle = new Bundle();  

  96.         mBundle.putSerializable("SeriableValue",mPerson);  

  97.         intent.putExtras(mBundle);  

  98.             

  99.         startActivity(intent);  

  100.         finish();  

  101.     }  

  102.   

  103. }  




Bundle02.java

[java] view plain copy print?在CODE上查看代碼片派生到個人代碼片

  1. package com.bundletest;  

  2.   

  3. import android.app.Activity;  

  4. import android.os.Bundle;    

  5. import android.view.View;  

  6. import android.view.View.OnClickListener;  

  7. import android.widget.Button;  

  8. import android.content.Intent;  

  9. import android.util.Log;  

  10.   

  11. public class Bundle02 extends Activity implements View.OnClickListener {  

  12.   

  13.     private static final String TAG = "skywang-->Bundle02";  

  14.   

  15.     private Button mBtnBack = null;  

  16.     @Override  

  17.     public void onCreate(Bundle savedInstanceState) {  

  18.         super.onCreate(savedInstanceState);  

  19.         setContentView(R.layout.main2);  

  20.   

  21.         mBtnBack = (Button) findViewById(R.id.btnBack);  

  22.         mBtnBack.setOnClickListener(this);  

  23.   

  24.         receiveBasicData();  

  25.         receiveParcelableData();  

  26.         receiveSeriableData();  

  27.     }  

  28.   

  29.     private void receiveBasicData() {  

  30.         Bundle bundle = this.getIntent().getExtras();    

  31.             

  32.         String name = bundle.getString("name");    

  33.         int height = bundle.getInt("height");  

  34.         if (name != null && height != 0)  

  35.         Log.d(TAG, "receice basic data -- " +  

  36.                    "name="+name+", height="+height);  

  37.     }  

  38.   

  39.     private void receiveParcelableData() {  

  40.         Book mBook = (Book)getIntent().getParcelableExtra("ParcelableValue");  

  41.         if (mBook != null)  

  42.             Log.d(TAG, "receice parcel data -- " +  

  43.                        "Book name is: " + mBook.getBookName()+", "+  

  44.                        "Author is: " + mBook.getAuthor() + ", "+  

  45.                        "PublishTime is: " + mBook.getPublishTime());  

  46.     }  

  47.   

  48.     private void receiveSeriableData() {  

  49.         Person mPerson = (Person)getIntent().getSerializableExtra("SeriableValue");    

  50.         if (mPerson != null)  

  51.             Log.d(TAG, "receice serial data -- " +  

  52.                        "The name is:" + mPerson.getName() + ", "+  

  53.                        "age is:" + mPerson.getAge());    

  54.     }  

  55.   

  56.     @Override  

  57.     public void onClick(View view) {  

  58.         switch (view.getId()) {  

  59.             case R.id.btnBack:  

  60.             {  

  61.                 // "com.test" is the package name of the destination class  

  62.                 // "com.test.Activity01" is the full class path of the destination class  

  63.                 Intent intent = new Intent().setClassName("com.bundletest""com.bundletest.Bundle01");  

  64.                 startActivity(intent);  

  65.                 // end current class  

  66.                 finish();  

  67.             }  

  68.                 break;  

  69.             default:  

  70.                 break;  

  71.   

  72.         }  

  73.     }  

  74.   

  75. }  




Book.java

[java] view plain copy print?在CODE上查看代碼片派生到個人代碼片

  1. package com.bundletest;  

  2.   

  3. import android.os.Parcel;    

  4. import android.os.Parcelable;    

  5.   

  6. public class Book implements Parcelable {    

  7.     private String bookName;    

  8.     private String author;    

  9.     private int publishTime;    

  10.         

  11.     public String getBookName() {    

  12.         return bookName;    

  13.     }    

  14.     public void setBookName(String bookName) {    

  15.         this.bookName = bookName;    

  16.     }    

  17.     public String getAuthor() {    

  18.         return author;    

  19.     }    

  20.     public void setAuthor(String author) {    

  21.         this.author = author;    

  22.     }    

  23.     public int getPublishTime() {    

  24.         return publishTime;    

  25.     }    

  26.     public void setPublishTime(int publishTime) {    

  27.         this.publishTime = publishTime;    

  28.     }    

  29.         

  30.     public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() {    

  31.         @Override  

  32.         public Book createFromParcel(Parcel source) {    

  33.             Book mBook = new Book();    

  34.             mBook.bookName = source.readString();    

  35.             mBook.author = source.readString();    

  36.             mBook.publishTime = source.readInt();    

  37.             return mBook;    

  38.         }    

  39.         @Override  

  40.         public Book[] newArray(int size) {    

  41.             return new Book[size];    

  42.         }    

  43.     };    

  44.         

  45.     @Override  

  46.     public int describeContents() {    

  47.         return 0;    

  48.     }    

  49.   

  50.     @Override  

  51.     public void writeToParcel(Parcel parcel, int flags) {    

  52.         parcel.writeString(bookName);    

  53.         parcel.writeString(author);    

  54.         parcel.writeInt(publishTime);    

  55.     }    

  56. }    




Person.java

[java] view plain copy print?在CODE上查看代碼片派生到個人代碼片

  1. package com.bundletest;  

  2.   

  3. import java.io.Serializable;    

  4.   

  5. public class Person implements Serializable {    

  6.   

  7.     private static final long serialVersionUID = 1L;   

  8.   

  9.     private String name;    

  10.     private int age;    

  11.     public String getName() {    

  12.         return name;    

  13.     }    

  14.     public void setName(String name) {    

  15.         this.name = name;    

  16.     }    

  17.     public int getAge() {    

  18.         return age;    

  19.     }    

  20.     public void setAge(int age) {    

  21.         this.age = age;    

  22.     }    

  23.         

  24. }    




 

5.3輸出圖片

Bundle01.java對應的界面以下:

 

點擊「Bundle Basic Data」、「Bundle Parcelable Data」、「Bundle Seriable Data」均跳轉到以下界面,但它們對應的logcat信息不一樣。


 

點擊「Bundle Basic Data」的logcat以下:


點擊「Bundle Parcelable Data」的logcat以下:


點擊「Bundle Seriable Data」的logcat以下:


轉自:http://www.cnblogs.com/skywang12345/archive/2013/03/06/3165555.html

相關文章
相關標籤/搜索