We may want to show the user a new screen in order to obtain some feedback before the current task can be completed.
Starting an activity so that we can get feedback is done through the StartActivityForResult()
method:
StartActivityForResult()
method:var intent = new Intent(this, typeof(ResultsActivity)); StartActivityForResult(intent, 1234);
OnActivityResult()
method:protected override void OnActivityResult( int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (requestCode == 1234) { if (resultCode == Result.Ok) { var value = data.GetStringExtra ("Key"); } else { // canceled } } }
SetResult()
method:var result = new Intent(); result.PutExtra("Key", "Some Value"); SetResult(Result.Ok, result); Finish();
Sometimes, we require feedback from an activity that was just displayed. To get this feedback, we have to launch the activity while letting the Android system know that we wish to be notified of the outcome of the user's actions.
Similar to launching activities just to display another screen, we create an intent that will launch the activity. But, instead of calling StartActivity
, we invoke the StartActivityForResult()
method along with an integer code. This code will be used to associate the start operation with the result of the new activity.
The user can then select an option or perform an operation on the second activity. Once the user has returned from the second activity, we will be notified of this in the first activity. In order to respond to these notifications, we override the OnActivityResult()
method.
In this method, we are provided with three pieces of data that we use to determine what happened in the activity that was just closed. The first piece is the request code, or the code that was specified when starting the activity. It is the value that was passed to the StartActivityForResult()
method. We use this to associate the result logic with the initial logic.
The next piece of data is the result code. This represents a value showing whether the activity was successful, canceled, or an error occurred. If the result code is Ok
, then the operation was successful and data was returned. If the result code is Canceled
, then either the user canceled the operation or an error occurred.
Finally, the last piece of data represents an intent that was specified by the second activity. This intent can be used to hold any data we wish either in the Data
property or in the various extras.
If we want to create an activity that can be used in this manner, we just need to set the result code and, optionally, an intent before the activity is terminated. This is done by passing a result code and an intent to the SetResult()
method.
This is usually followed by the Finish()
method to let the Android system know that the activity should now be terminated. If no result is specified before the activity is terminated, then the result is automatically set to Canceled
.