《Android 应用案例开发大全(第二版)》——6.8节传递附加数据(Extra)

本节书摘来自异步社区《Android 应用案例开发大全(第二版)》一书中的第6章,第6.8节传递附加数据(Extra) ,作者李宁,更多章节内容可以访问云栖社区“异步社区”公众号查看

6.8 传递附加数据(Extra)
Android开发权威指南(第二版)
在显示窗口时通常可以使用如下两种方式向窗口传递数据。

通过Data传递数据。
通过putExtra传递附加数据。
第1种方法在前面已经多次使用过了,通过Data传递数据实际上就是通过Uri将数据传递给窗口。例如,传递电话号可以用“tel:12345678”。第1种方式虽然传递数据比较方便,但只能传递有限的数据,如果要传递的数据量比较大,而且数据类型比较多(如int、boolean、byte[]等类型),就要使用第2种方式传递附加数据。

Intent类有多个重载的putExtra方法,这些方法用于向Intent对象写入不同类型的数据,putExtra方法有两个参数,第1个参数是key,第2个参数是value。也就是putExtra方法会将一个key-value,类型的数据存入Intent对象,然后Intent.getXxxExtra方法可以通过key获取value。其中Xxx表示Int、Char、String等。例如,getIntExtra、getCharExtra和getStringExtra都是这种类型的方法。getXxxExtra方法也有两个参数1,第1个参数是key,第2个参数是defaultValue。当Intent对象中没有key时就返回defaultValue。

下面的代码使用putExtra方法写入了String、int和char类型的数据,并使用getXxxExtra方法获取了这些数据。

// 写入附加数据
Intent intent = new Intent(this, MyActivity.class);
intent.putExtra("key1", 20);
intent.putExtra("key2", 'c');
intent.putExtra("key3","value");

// 读取附加数据
// 0是默认值
int n = intent.getIntExtra("key1", 0);
// 'c'是默认值
char c = intent.getCharExtra("key2", 'c');
String s = intent.getStringExtra("key3");
除了可以使用Intent.putExtra设置附加数据外,还可以使用Bundle对象设置完附加数据后,使用Intent.putExtras方法设置一个Bundle对象,代码如下:

// 写入附加数据
Intent intent = new Intent(this, MyActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("key1", 20);
bundle.putChar("key2", 'c');
bundle.putString("key3", "value");
intent.putExtras(bundle);

读取通过Bundle对象写入的数据时可以用Intent.getXxxExtra方法,也可以通过Intent.getExtras方法获取Bundle对象后,然后再通过Bundle.get或Bundle.getXxx方法(其中Xxx表示String、Int等字符串)获取相应的数据。其中Bundle.get方法只返回一个Object对象,可以封装任何类型的数据。而Bundle.getXxx方法通常有两个重载形式,一个没有默认值(只有一个参数用于传递key),另外一个有两个参数,一个是key,另一个是defaultValue。

实际上,Intent.putExtra和Bundle.putXxx方法本质上是一样的,如果不用Intent.putExtras方法设置Bundle对象,Intent会在内部创建一个新的Bundle对象。如果设置了Bundle对象,Intent就直接使用该Bundle对象。这一点从Intent.putExtra和Intent.putExtras方法的源代码就可以看出。

public Intent putExtra(String name, String value) 
{
  if (mExtras == null) 
{
    mExtras = new Bundle();
  }
  mExtras.putString(name, value)**;**
  return this;
}
public Intent putExtras(Bundle extras) 
{
  if (mExtras == null) 
  {
    mExtras = new Bundle();
  }
  // 将extras中的key-value对都添加到内部的Bundle对象中(mExtras)
    mExtras.putAll(extras);
  return this;
}

要注意的是,如果通过key获取的value的数据类型与返回值数据类型不同时,并不会进行类型转换,而会返回默认值,或返回null(对于字符串类型的value)。例如,下面的代码中尽管key存在,但由于类型不匹配,所以仍然返回int的默认值。

Intent intent = new Intent();
// value的数据类型是String
intent.putExtra("key", "40");
// n的值为120(默认值)
int n = intent.getIntExtra("key", 120);

1 getStringExtra方法是个例外,该方法只有一个参数,没有默认值。

上一篇:《Android应用开发与系统改造实战》——1.3节Android开发所需软件的下载


下一篇:《Android 应用案例开发大全(第二版)》——6.9节解析数据