---
title: "Android-------Activity之间通信"
author: "marine8888"
date: "2011-01-17T09:23:44Z"
tags: []
categories: ["移动开发"]
slug: "android-activity"
draft: false
lastmod: "2011-01-17T09:23:44Z"
id: 876048
url: "https://androidstudy.iteye.com/blog/876048"
---

FROM：[http://www.ibm.com/developerworks/cn/opensource/os-cn-android-actvt/index.html](http://www.ibm.com/developerworks/cn/opensource/os-cn-android-actvt/index.html)

[Activity 之间通信]()

[使用 Intent 通信]()

在 Android 中，不同的 Activity 实例可能运行在一个进程中，也可能运行在不同的进程中。因此我们需要一种特别的机制帮助我们在 Activity 之间传递消息。Android 中通过 Intent 对象来表示一条消息，一个 Intent 对象不仅包含有这个消息的目的地，还可以包含消息的内容，这好比一封 Email，其中不仅应该包含收件地址，还可以包含具体的内容。对于一个 Intent 对象，消息“目的地”是必须的，而内容则是可选项。

在上面的实例中通过 *Activity. startActivity(intent)*启动另外一个 Activity 的时候，我们在 Intent 类的构造器中指定了“收件人地址”。

如果我们想要给“收件人”Activity 说点什么的话，那么可以通过下面这封“e-mail”来将我们消息传递出去：

```
 Intent intent =new Intent(CurrentActivity.this,OtherActivity.class);
  // 创建一个带“收件人地址”的 email 
 Bundle bundle =new Bundle();// 创建 email 内容
 bundle.putBoolean("boolean_key", true);// 编写内容
 bundle.putString("string_key", "string_value"); 
 intent.putExtra("key", bundle);// 封装 email 
 startActivity(intent);// 启动新的 Activity 
```

那么“收件人”该如何收信呢？在 *OtherActivity*类的 *onCreate()*或者其它任何地方使用下面的代码就可以打开这封“e-mail”阅读其中的信息：

```
 Intent intent =getIntent();// 收取 email 
 Bundle bundle =intent.getBundleExtra("key");// 打开 email 
 bundle.getBoolean("boolean_key");// 读取内容
 bundle.getString("string_key"); 
```

上面我们通过 *bundle*对象来传递信息，*bundle*维护了一个 *HashMap&lt;String, Object&gt;*对象，将我们的数据存贮在这个 HashMap 中来进行传递。但是像上面这样的代码稍显复杂，因为 Intent 内部为我们准备好了一个 *bundle*，所以我们也可以使用这种更为简便的方法：

```
 Intent intent =new Intent(EX06.this,OtherActivity.class); 
 intent.putExtra("boolean_key", true); 
 intent.putExtra("string_key", "string_value"); 
 startActivity(intent); 
```

接收：

```
 Intent intent=getIntent(); 
 intent.getBooleanExtra("boolean_key",false); 
 intent.getStringExtra("string_key"); 
```

```

```