Android中Bundle和Intent的区别

时间:2023-11-28 00:00:32

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就显得不专业,不灵活的多