Android Bundle总结
1 Bundle介绍
Bundle主要用于传递数据;它保存的数据,是以key-value(键值对)的形式存在的。
我们经常使用Bundle在Activity之间传递数据,传递的数据可以是boolean、byte、int、long、float、double、string等基本类型或它们对应的数组,也可以是对象或对象数组。当Bundle传递的是对象或对象数组时,必须实现Serializable 或Parcelable接口。下面分别介绍Activity之间如何传递基本类型、传递对象。
2传递基本类型
Bundle提供了各种常用类型的putXxx()/getXxx()方法,用于读写基本类型的数据。Bundle操作基本数据类型的API表格如下所示:
[外链图片转存失败(img-25OxIrpc-1562049160656)()]
写数据的方法如下:
[java] view plain copy print ?
1. // "com.test" is the package name of the destination class
2. // "com.test.Activity02" is the full class path of the destination class
3. Intent intent = new Intent().setClassName("com.bundletest", "com.bundletest.Bundle02");
4.
5. Bundle bundle = new
6. bundle.putString("name", "skywang");
7. bundle.putInt("height", 175);
8. intent.putExtras(bundle);
9.
10. startActivity(intent);
11.
12. // end current class
13. finish();
// "com.test" is the package name of the destination class
// "com.test.Activity02" is the full class path of the destination class
Intent intent = new Intent().setClassName("com.bundletest", "com.bundletest.Bundle02");
Bundle bundle = new Bundle();
bundle.putString(“name”, “skywang”);
bundle.putInt(“height”, 175);
intent.putExtras(bundle);startActivity(intent);
// end current class
finish();
对应的读数据的方法如下:
[java] view plain copy print ?
1. Bundle bundle = this.getIntent().getExtras();
2.
3. String name = bundle.getString("name");
4. int height = bundle.getInt("height");
Bundle bundle = this.getIntent().getExtras();
String name = bundle.getString(“name”);
int height = bundle.getInt(“height”);
3传递Parcelable类型的对象
3.1 Parcelable说明
Parcelable是Android自定义的一个接口,它包括了将数据写入Parcel和从Parcel中读出的API。一个实体(用类来表示),如果需要封装到bundle消息中去,可以通过实现Parcelable接口来实现。
Parcelable和Serializable的API如下表:
[外链图片转存失败(img-jsycNkVH-1562049160657)()]
3.2 Parcelable接口说明
[java] view plain copy print ?
1. public interface
2. //内容描述接口,基本不用管
3. public int
4. //写入接口函数,打包
5. public void writeToParcel(Parcel dest, int
6. //读取接口,目的是要从Parcel中构造一个实现了Parcelable的类的实例处理。因为实现类在这里还是不可知的,所以需要用到模板的方式,继承类名通过模板参数传入。
7. //为了能够实现模板参数的传入,这里定义Creator嵌入接口,内含两个接口函数分别返回单个和多个继承类实例。
8. public interface
9. public
10. public T[] newArray(int
11. }
12. }
public interface Parcelable {
//内容描述接口,基本不用管
public int describeContents();
//写入接口函数,打包
public void writeToParcel(Parcel dest, int flags);
//读取接口,目的是要从Parcel中构造一个实现了Parcelable的类的实例处理。因为实现类在这里还是不可知的,所以需要用到模板的方式,继承类名通过模板参数传入。
//为了能够实现模板参数的传入,这里定义Creator嵌入接口,内含两个接口函数分别返回单个和多个继承类实例。
public interface Creator<T> {
public T createFromParcel(Parcel source);
public T[] newArray(int size);
}
}
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文件
工程文件结构如下所示:
[外链图片转存失败(img-xRQ75Vt1-1562049160658)()]
5.2代码
AndroidManifest.xml
[html] view plain copy print ?
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>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bundletest"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Bundle01"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Bundle02"> </activity>
</application>
<uses-sdk android:minSdkVersion="11" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Bundle01"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Bundle02"> </activity>
</application>
<uses-sdk android:minSdkVersion="11" />
</manifest>
main.xml
[html] view plain copy print ?
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>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/app_01"
/>
<Button
android:id="@+id/btnBasic"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/text_basic"
/>
<Button
android:id="@+id/btnPar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/text_par"
/>
<Button
android:id="@+id/btnSer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/text_ser"
/>
<Button
android:id="@+id/btnBasic"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/text_basic"
/>
<Button
android:id="@+id/btnPar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/text_par"
/>
<Button
android:id="@+id/btnSer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/text_ser"
/>
</LinearLayout>
main2.xml
[html] view plain copy print ?
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>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/app_02"
/>
<Button
android:id="@+id/btnBack"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/text_jump_back"
/>
<Button
android:id="@+id/btnBack"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/text_jump_back"
/>
</LinearLayout>
strings.xml
[html] view plain copy print ?
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>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello MyBundleTest!</string>
<string name="app_name">MyBundleTest</string>
<string name="app_01">Bundle_01</string>
<string name="app_02">Bundle_02</string>
<string name="text_basic">Bundle Basic Data</string>
<string name="text_par">Bundle Parcelable Data</string>
<string name="text_ser">Bundle Seriable Data</string>
<string name="text_jump_back">Jump Back to Bundler01</string>
</resources>
Bundle01.java
[java] view plain copy print ?
1. package
2.
3. import
4. import
5. import
6. import
7. import
8. import
9. import
10.
11. public class Bundle01 extends Activity implements
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
21. super.onCreate(savedInstanceState);
22. setContentView(R.layout.main);
23.
24. mBtnBasic = (Button) findViewById(R.id.btnBasic);
25. this);
26.
27. mBtnPar = (Button) findViewById(R.id.btnPar);
28. this);
29.
30. mBtnSer = (Button) findViewById(R.id.btnSer);
31. this);
32. }
33.
34.
35. @Override
36. public void
37. switch
38. case
39. sendBasicDataThroughBundle();
40. break;
41. case
42. sendParcelableDataThroughBundle();
43. break;
44. case
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
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. new Intent().setClassName("com.bundletest", "com.bundletest.Bundle02");
58.
59. new
60. "name", "skywang");
61. "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
72. new Intent().setClassName("com.bundletest", "com.bundletest.Bundle02");
73.
74. new
75. "Android");
76. "skywang");
77. 2013);
78.
79. new
80. "ParcelableValue", mBook);
81. intent.putExtras(mBundle);
82.
83. startActivity(intent);
84. finish();
85. }
86.
87. // sent object through seriable
88. private void
89. new Intent().setClassName("com.bundletest", "com.bundletest.Bundle02");
90.
91. new
92. "skywang");
93. 24);
94.
95. new
96. "SeriableValue",mPerson);
97. intent.putExtras(mBundle);
98.
99. startActivity(intent);
100. finish();
101. }
102.
103. }
package com.bundletest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.content.Intent;
import android.util.Log;
public class Bundle01 extends Activity implements View.OnClickListener{
private static final String TAG = "skywang-->Bundle01";
private Button mBtnBasic = null;
private Button mBtnPar = null;
private Button mBtnSer = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mBtnBasic = (Button) findViewById(R.id.btnBasic);
mBtnBasic.setOnClickListener(this);
mBtnPar = (Button) findViewById(R.id.btnPar);
mBtnPar.setOnClickListener(this);
mBtnSer = (Button) findViewById(R.id.btnSer);
mBtnSer.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnBasic:
sendBasicDataThroughBundle();
break;
case R.id.btnPar:
sendParcelableDataThroughBundle();
break;
case R.id.btnSer:
sendSeriableDataThroughBundle();
break;
default:
break;
}
}
// sent basic data, such as int, strin, etc... through bundle
private void sendBasicDataThroughBundle(){
// "com.test" is the package name of the destination class
// "com.test.Activity02" is the full class path of the destination class
Intent intent = new Intent().setClassName("com.bundletest", "com.bundletest.Bundle02");
Bundle bundle = new Bundle();
bundle.putString("name", "skywang");
bundle.putInt("height", 175);
intent.putExtras(bundle);
startActivity(intent);
// end current class
finish();
}
// sent object through Pacelable
private void sendParcelableDataThroughBundle(){
Intent intent = new Intent().setClassName("com.bundletest", "com.bundletest.Bundle02");
Book mBook = new Book();
mBook.setBookName("Android");
mBook.setAuthor("skywang");
mBook.setPublishTime(2013);
Bundle mBundle = new Bundle();
mBundle.putParcelable("ParcelableValue", mBook);
intent.putExtras(mBundle);
startActivity(intent);
finish();
}
// sent object through seriable
private void sendSeriableDataThroughBundle(){
Intent intent = new Intent().setClassName("com.bundletest", "com.bundletest.Bundle02");
Person mPerson = new Person();
mPerson.setName("skywang");
mPerson.setAge(24);
Bundle mBundle = new Bundle();
mBundle.putSerializable("SeriableValue",mPerson);
intent.putExtras(mBundle);
startActivity(intent);
finish();
}
}
Bundle02.java
[java] view plain copy print ?
1. package
2.
3. import
4. import
5. import
6. import
7. import
8. import
9. import
10.
11. public class Bundle02 extends Activity implements
12.
13. private static final String TAG = "skywang-->Bundle02";
14.
15. private Button mBtnBack = null;
16. @Override
17. public void
18. super.onCreate(savedInstanceState);
19. setContentView(R.layout.main2);
20.
21. mBtnBack = (Button) findViewById(R.id.btnBack);
22. this);
23.
24. receiveBasicData();
25. receiveParcelableData();
26. receiveSeriableData();
27. }
28.
29. private void
30. this.getIntent().getExtras();
31.
32. "name");
33. int height = bundle.getInt("height");
34. if (name != null && height != 0)
35. "receice basic data -- "
36. "name="+name+", height="+height);
37. }
38.
39. private void
40. "ParcelableValue");
41. if (mBook != null)
42. "receice parcel data -- "
43. "Book name is: " + mBook.getBookName()+", "+
44. "Author is: " + mBook.getAuthor() + ", "+
45. "PublishTime is: "
46. }
47.
48. private void
49. "SeriableValue");
50. if (mPerson != null)
51. "receice serial data -- "
52. "The name is:" + mPerson.getName() + ", "+
53. "age is:"
54. }
55.
56. @Override
57. public void
58. switch
59. case
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. 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. }
package com.bundletest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.content.Intent;
import android.util.Log;public class Bundle02 extends Activity implements View.OnClickListener {
private static final String TAG = "skywang-->Bundle02";
private Button mBtnBack = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
mBtnBack = (Button) findViewById(R.id.btnBack);
mBtnBack.setOnClickListener(this);
receiveBasicData();
receiveParcelableData();
receiveSeriableData();
}
private void receiveBasicData() {
Bundle bundle = this.getIntent().getExtras();
String name = bundle.getString("name");
int height = bundle.getInt("height");
if (name != null && height != 0)
Log.d(TAG, "receice basic data -- " +
"name="+name+", height="+height);
}
private void receiveParcelableData() {
Book mBook = (Book)getIntent().getParcelableExtra("ParcelableValue");
if (mBook != null)
Log.d(TAG, "receice parcel data -- " +
"Book name is: " + mBook.getBookName()+", "+
"Author is: " + mBook.getAuthor() + ", "+
"PublishTime is: " + mBook.getPublishTime());
}
private void receiveSeriableData() {
Person mPerson = (Person)getIntent().getSerializableExtra("SeriableValue");
if (mPerson != null)
Log.d(TAG, "receice serial data -- " +
"The name is:" + mPerson.getName() + ", "+
"age is:" + mPerson.getAge());
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnBack:
{
// "com.test" is the package name of the destination class
// "com.test.Activity01" is the full class path of the destination class
Intent intent = new Intent().setClassName("com.bundletest", "com.bundletest.Bundle01");
startActivity(intent);
// end current class
finish();
}
break;
default:
break;
}
}
}
Book.java
[java] view plain copy print ?
1. package
2.
3. import
4. import
5.
6. public class Book implements
7. private
8. private
9. private int
10.
11. public
12. return
13. }
14. public void
15. this.bookName = bookName;
16. }
17. public
18. return
19. }
20. public void
21. this.author = author;
22. }
23. public int
24. return
25. }
26. public void setPublishTime(int
27. this.publishTime = publishTime;
28. }
29.
30. public static final Parcelable.Creator<Book> CREATOR = new
31. @Override
32. public
33. new
34. mBook.bookName = source.readString();
35. mBook.author = source.readString();
36. mBook.publishTime = source.readInt();
37. return
38. }
39. @Override
40. public Book[] newArray(int
41. return new
42. }
43. };
44.
45. @Override
46. public int
47. return 0;
48. }
49.
50. @Override
51. public void writeToParcel(Parcel parcel, int
52. parcel.writeString(bookName);
53. parcel.writeString(author);
54. parcel.writeInt(publishTime);
55. }
56. }
package com.bundletest;
import android.os.Parcel;
import android.os.Parcelable;public class Book implements Parcelable {
private String bookName;
private String author;
private int publishTime;
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getPublishTime() {
return publishTime;
}
public void setPublishTime(int publishTime) {
this.publishTime = publishTime;
}
public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() {
@Override
public Book createFromParcel(Parcel source) {
Book mBook = new Book();
mBook.bookName = source.readString();
mBook.author = source.readString();
mBook.publishTime = source.readInt();
return mBook;
}
@Override
public Book[] newArray(int size) {
return new Book[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeString(bookName);
parcel.writeString(author);
parcel.writeInt(publishTime);
}
}
Person.java
[java] view plain copy print ?
1. package
2.
3. import
4.
5. public class Person implements
6.
7. private static final long
8.
9. private
10. private int
11. public
12. return
13. }
14. public void
15. this.name = name;
16. }
17. public int
18. return
19. }
20. public void setAge(int
21. this.age = age;
22. }
23.
24. }
package com.bundletest;
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
5.3输出图片
Bundle01.java对应的界面如下:
[外链图片转存失败(img-A0mdERs6-1562049160661)()]
点击“Bundle Basic Data”、“Bundle Parcelable Data”、“Bundle Seriable Data”均跳转到如下界面,但它们对应的logcat信息不同。
[外链图片转存失败(img-cYon5gYr-1562049160662)()]
点击“Bundle Basic Data”的logcat如下:
[外链图片转存失败(img-2mkOGWbp-1562049160664)()]
点击“Bundle Parcelable Data”的logcat如下:
[外链图片转存失败(img-C2f0T87S-1562049160665)()]
点击“Bundle Seriable Data”的logcat如下:
[外链图片转存失败(img-QwEFTYtG-1562049160666)()]