---
title: "使用Bundle在Activity间传递数据"
author: "可爱多"
date: "2011-01-06T00:14:42Z"
tags: []
categories: ["移动开发"]
slug: "bundle-activity"
draft: false
lastmod: "2011-01-06T00:25:26Z"
id: 860192
url: "https://bye.iteye.com/blog/860192"
---

**使用Bundle 在Activity 间传递数据1：**

**1.1从源Activity 中传递数据**
//数据写入Intent
*<span style="color:darkblue">Intent openWelcomeActivityIntent=new Intent();
Bundle myBundelForName=new Bundle();
myBundelForName.putString("Key_Name",inName.getText().toString());
myBundelForName.putString("Key_Age",inAge.getText().toString());
openWelcomeActivityIntent.putExtras(myBundelForName);
openWelcomeActivityIntent.setClass(AndroidBundel.this, Welcome.class);
startActivity(openWelcomeActivityIntent);</span>*

**1.2目标Activity 中获取数据**
//从Intent 中获取数据
*<span style="color:darkblue">Bundle myBundelForGetName=this.getIntent().getExtras();
String name=myBundelForGetName.getString("Key_Name");
myTextView_showName.setText("欢迎您进入："+name);</span>*

**使用Bundle 在Activity 间传递数据2：**
2.1从源请求Activity 中通过一个Intent 把一个服务请求传到目标Activity 中
//从Intent 中获取数据
<span style="color:darkblue">*Bundle myBundelForGetName=this.getIntent().getExtras();
String name=myBundelForGetName.getString("Key_Name");
myTextView_showName.setText("欢迎您进入："+name);
private Intent toNextIntent;//Intent 成员声明
toNextIntent=new Intent();//Intent 定义
toNextIntent.setClass(TwoActivityME3.this, SecondActivity3.class);*</span>
//设定开启的下一个Activity
<span style="color:darkblue">*startActivityForResult(toNextIntent, REQUEST_ASK););</span>*

2.2开启Intent 时候，把请求码同时传递在源请求Activity 中等待Intent 返回应答结果，通过重载onActivityResult()方法
<span style="color:darkblue">*@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if(requestCode==REQUEST_ASK){
    if(resultCode==RESULT_CANCELED){
      setTitle("Cancel****");
    }else if(resultCode==RESULT_OK){
      showBundle=data.getExtras();//从返回的Intent中获得Bundle
      Name=showBundle.getString("myName");//从bundle中获得相应数据
       text.setText("the name get from the second layout:\n"+Name);
     }
    }
 }
</span>*
☻ 第一个参数是你开启请求Intent时的对应请求码，可以自己定义。
☻ 第二个参数是目标Activity返回的验证结果码
☻ 第三个参数是目标Activity返回的Intent
2.3目标Activity 中发送请求结果代码，连同源Activity 请求的数据一同绑定到Bundle
中通过Intent 传回源请求Activity 中
<span style="color:darkblue">*backIntent=new Intent();
stringBundle=new Bundle();
stringBundle.putString("myName", Name);
backIntent.putExtras(stringBundle);
setResult(RESULT_OK, backIntent);//返回Activity结果码
finish(););</span>*