Android 在两个 Activity 之间传递数据
调用方 Activity:
public void callActivity {
// 将数据包装并传入被调方 Activity
Intent intent = new Intent();
intent.setClass(this, TestActivity2.class);
Bundle bundle = new Bundle();
bundle.putString("data", "data");
intent.putExtras(bundle);
this.startActivityForResult(intent, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// 接收被调方 Activity 返回的数据
switch (resultCode) {
case RESULT_OK:
String data = data.getExtras().getString("data");
break;
}
}
被调方 Activity:
public void returnData() {
Intent in = this.getIntent();
Bundle bn = in.getExtras();
bn.putString("data", "return data");
in.putExtras(bn);
this.setResult(RESULT_OK, in);
}
public void callActivity {
// 将数据包装并传入被调方 Activity
Intent intent = new Intent();
intent.setClass(this, TestActivity2.class);
Bundle bundle = new Bundle();
bundle.putString("data", "data");
intent.putExtras(bundle);
this.startActivityForResult(intent, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// 接收被调方 Activity 返回的数据
switch (resultCode) {
case RESULT_OK:
String data = data.getExtras().getString("data");
break;
}
}
被调方 Activity:
public void returnData() {
Intent in = this.getIntent();
Bundle bn = in.getExtras();
bn.putString("data", "return data");
in.putExtras(bn);
this.setResult(RESULT_OK, in);
}