向下一个应用传递数据
1 button1.setOnClickListener(new View.OnClickListener(){ 2 @Override 3 public void onClick(View v) { 4 String data = "你好呀,SecondActivity"; 5 Intent intent = new Intent(FirstActivity.this,SecondActivity.class); 6 intent.putExtra("extra_data",data);//第一个参数是键,第二个参数才是真正的数据 7 startActivity(intent); 8 } 9 });
在SecondActivity重写的onCreate方法中,加入如下代码:
1 @Override 2 protected void onCreate(Bundle savedInstanceState) { 3 super.onCreate(savedInstanceState); 4 setContentView(R.layout.second_layout); 5 Intent intent = getIntent();//注意这里是getIntent() 6 String data = intent.getStringExtra("extra_data"); 7 Log.d("SecondActivity",data); 8 //···· 9 }
返回数据给上一个活动
1 button1.setOnClickListener(new View.OnClickListener(){ 2 @Override 3 public void onClick(View v) { 4 Intent intent = new Intent(FirstActivity.this,SecondActivity.class); 5 startActivityForResult(intent,1); 6 } 7 });
1 Button button2 = (Button)findViewById(R.id.button_2); 2 button2.setOnClickListener(new View.OnClickListener(){ 3 @Override 4 public void onClick(View v) { 5 Intent intent = new Intent(); 6 intent.putExtra("data_return","你好呀 FirstActivity"); 7 setResult(RESULT_OK,intent); 8 finish(); 9 } 10 });
在FirstActivity中重写onActivityResult()方法来得到返回数据:
1 @Override 2 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 3 switch (requestCode){ 4 case 1: 5 if(resultCode == RESULT_OK){ 6 String returnedData = data.getStringExtra("data_return"); 7 Log.d("FirstActivity",returnedData); 8 } 9 break; 10 default: 11 } 12 super.onActivityResult(requestCode, resultCode, data); 13 }
如果用户不是通过点击button 2按钮返回到FirstActivity,而是通过按下手机的Back键回到FirstActivity,这个时候我们就要监听Back键来发送数据给上层应用了:
1 @Override 2 public void onBackPressed(){ 3 Intent intent = new Intent(); 4 intent.putExtra("data_return","你好呀,,,FirstActivity"); 5 setResult(RESULT_OK,intent); 6 finish(); 7 }