活动 1
创建一个类变量以供参考。
private final int REQUEST_CODE = 0;
...
//Somewhere in your code you have to call startActivityForResult
Intent intent = new Intent(Activity1.this, Activity2.class);
startActivityForResult(intent);
活动二
在结束 Activity2 之前,您必须将结果设置为 OK 并将要带回 Activity1 的数据 likeso
Intent data = new Intent();
data.putExtra("name", "Mark");
data.putExtra("number", 1);
data.putExtra("areYouHappy", true);
setResult(RESULT_OK, data);
finish(); //closes Activity2 and goes back to Activity1
现在回到 Activity1,您应该重写 onActivityResult 方法并从 Activity2 中检索值。
为此,首先检查 Activity2 的结果是否正常,然后检查您传递的参考 REQUEST_CODE。由于之前我们创建了 private final int REQUEST_CODE = 0
,然后我们检查 requestCode 是否等于变量 REQUEST_CODE。如果是,则从活动 2 中提取数据。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK) {
if(requestCode==REQUEST_CODE) {
if(data.getExtras()!=null) {
String name = data.getStringExtra("name");
int number = data.getIntExtra("number",0); //2nd parameter is the default value in case "number" does not exist
boolean areYouHappy = data.getBooleanExtra("areYouHappy", false); //2nd parameter is the default value in case "areYouHappy" does not exist
}
}
}
}