Activity传递数据

一、A—>B方式

 1 // A
 2 
 3 // 创建意图时添加
 4 
 5 intent.putExtra("key","value");
 6 
 7 ...
 8 
 9 // B
10 
11 // 获取意图
12 
13 Intent intent = getIntent();
14 
15 intent.getString("key");


二、A—>B(批量)

 1 // A
 2 
 3 // 添加
 4 
 5 Bundle bundle = new Bundle();
 6 
 7 bundle.putString("key","value");
 8 
 9 ...
10 
11 // B
12 
13 // 获取
14 
15 Bundle bundle = intent.getExtras();
16 
17 bundle.getString("key");


三、A—>B—>A

 1 // A
 2 
 3 private static final String BLACK_RESULT = 0;
 4 
 5 Intent intent = new Intent(this,BlackActivity.class);
 6 
 7 Bundle bundle = new Bundle();
 8 
 9 bundle.putString("replay",replay);
10 
11 intent.putExtras(bundle);
12 
13 this.startActivityForResult(intent,BLACK_RESULT); 
14 
15 ...
16 
17 
18 // B
19 
20 // 获取A的数据
21 
22 Bundle bundle = this.getIntent().getExtras();
23 
24 replay = bundle.getString("replay");
25 
26 ...
27 
28 // 创建意图,返回数据
29 
30 Intent intent = new Intent();
31 
32 Bundle bundle = new Bundle();
33 
34 bundle.putString("replay",replay);
35 
36 intent.putExtras(bundle);
37 
38 this.setResult(RESULT_OK,intent);
39 
40 this.finish(); 

  以上已经完成A到B以及B发送数据的过程,下面A处理接收B的数据

 1 //重新A的方法
 2 
 3 @Override
 4 
 5 protected void onActivityResult(int requestCode,int resultCode,Intent data){
 6 
 7 switch(resultCode){
 8 
 9 case RESULT_OK:
10 
11 Bundle b = data.getExtras();
12 
13 replay = b.getString("replay");
14 
15 }
16 
17 }
18 
19 //为了使程序完善,重写B的返回键
20 
21 @Override
22 
23 public boolean onKeyDown(int keyCode, KeyEvent event) {
24 
25 if (keyCode == KeyEvent.KEYCODE_BACK &&
26 
27         event.getRepeatCount() == 0) {
28 
29 replaySend();
30 
31 return true;
32 
33 } else
34 
35 return super.onKeyDown(keyCode, event);
36 
37 }

 

posted @ 2013-04-02 13:03  轻云沉峰  阅读(165)  评论(0编辑  收藏  举报