Sometimes, we want some pages bring some data after closing it, e.g., returning the phone number of someone.
The mainstream way is to use Activity Result API. However, in some old tutorials, startActivityForResult, onActivityResult() might be used.
Activity Result API
Activity result API is introduced to simply the procedure of returning results and decouple components. The core includes:
ActivityResultContract
which defines how to create Intent and how to parse the returned result Intent.
ActivityResultLauncher
We should first call registerForActivityResult() to register a contract and a callback, to get this launcher. Then invoking the launch() method of this launcher to start target activity.
ActivityResultCallback.
When the target activity returns, this callback will be triggered, which can be exploited to handle returned data.
Concrete Steps
Register at source activity.
This registration must be done at onCreate() or member declaration, not runtime logics.
// retrieve data passed from source activity Stringgreeting= getIntent().getStringExtra("GREETING"); returnButton.setOnClickListener(v -> { Stringinput= editText.getText().toString();
// a. create an empty Intent to store data for return IntentreturnIntent=newIntent(); // b. put data into intent returnIntent.putExtra("RETURN_DATA", input);
// c. set result_code and returned intent setResult(Activity.RESULT_OK, returnIntent);