Android:Intent传递数据
接收调用的Activity销毁后返回的数据
调用MainActivity中:显式Intent调用并设置requestCode为1,在回调函数中接收返回的数据。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.button_exit);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, TestActivity.class);
startActivityForResult(intent, 1);
}
});
}
//调用的Activity销毁返回后执行的回调方法
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
if(resultCode == RESULT_OK){
String value = data.getStringExtra("key");
Log.d("debug", value);
}
break;
default:
break;
}
}
}
被调用Activity中:通过两种不同形式返回不同数据(按button返回和按系统返回键返回)
public class TestActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Button button = (Button)findViewById(R.id.test_button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("key", "value_data_button");
setResult(RESULT_OK, intent);
finish();
}
});
}
//系统返回键事件处理函数
@Override
public void onBackPressed() {
Intent intent = new Intent();
intent.putExtra("key", "value_data_backpressed");
setResult(RESULT_OK, intent);
finish();
}
}