(A) who
Description: Yes, that is startActivityForResult () method, which is used to return data in the event is destroyed when given on a method.
Parameters:
the startActivityForResult (Intent,. 1) The first argument is the Intent, the second parameter is the request code, for determining the source of the data.
(B) what
are now two activity, activityA and activityB, activityA activityB want to send request to have actiivtyB return data.
code show as below:
public class ActivityA extends AppCompatActivity { private Button sendBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_a); sendBtn = findViewById(R.id.send_btn); sendBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(ActivityA.this, ActivityB.class ); // first parameter is the Intent, the second parameter is the request code, randomly defined, guaranteed to be unique on the line the startActivityForResult (Intent,. 1 ); } }); } @Override protected void the onActivityResult ( int requestCode, int the resultCode, the Intent data) { Super .onActivityResult (requestCode, the resultCode, data); // here to determine the source of the data for a request code via Switch (requestCode) { Case . 1 : // result of the determination request is successful, resultCode == RESULT_OK , on behalf of the success of the IF (resultCode == RESULT_OK) { String getData = data.getStringExtra("data"); Toast.makeText(ActivityA.this, getData, Toast.LENGTH_LONG).show(); } break; /**这里可以有多个requestcode**/ default: } } }
Here is activityB
public class ActivityB extends AppCompatActivity{ private Button returnData; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_b); returnData = findViewById(R.id.return_data); returnData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(); //To be passed to the data stored in the intent activityA in intent.putExtra ( "data", "Hello, Time" ); // upwardly activity returns a result of the first parameter, and in general there are two values RESULT_OK RESULT_CANCEL, first two parameters with the intent to pass the data back setResult (RESULT_OK, intent); Finish (); } }); } }
Note: When the user points back key, the data does not return back, this time we should rewrite onBackPressed () method of
@Override public void onBackPressed() { Intent intent = new Intent(); intent.putExtra("data", "你好,time"); setResult(RESULT_OK, intent); finish(); }