/// <summary> /// Instead of calling "StarterActivity.StartActivityForResult()" directly, we call this /// awaitable method, which takes care about waiting for the Android event. If the Intent /// is never finished, the method would not return, but usually this results in a cancel /// result. /// </summary> /// <param name="intentToStart">New indent we want to start, this could for example be a /// file dialog intent.</param> /// <returns>Returns the result of the started and awaited intent.</returns> public async Task <ActivityResult> StartActivityAndWaitForResult(Intent intentToStart) { unchecked { _requestCode++; } StartedActivityInfo activityInfo = new StartedActivityInfo { RequestCode = _requestCode, WaitHandle = new ManualResetEvent(false) }; _startedActivityInfos.Add(activityInfo); // Prepare the waiting task Task <ActivityResult> waiterTask = new Task <ActivityResult>(() => { // Start the activity StarterActivity.StartActivityForResult(intentToStart, activityInfo.RequestCode); activityInfo.WaitHandle.WaitOne(); return(activityInfo.Result); }); // Start the waiting waiterTask.Start(); return(await waiterTask); }
/// <summary> /// The StarterActivity should overwrite the "OnActivityResult()" method and redirect its /// parameter directly to this method. Afterwards it can call base.OnActivityResult(). /// </summary> /// <param name="requestCode">The requestCode passed to the StarterActivity.</param> /// <param name="resultCode">The resultCode passed to the StarterActivity.</param> /// <param name="data">The data passed to the StarterActivity.</param> public void OnActivityResult(int requestCode, Result resultCode, Intent data) { // Lets see if we have started an activity with this request code. StartedActivityInfo activityInfo = _startedActivityInfos.Find(item => item.RequestCode == requestCode); if (activityInfo != null) { _startedActivityInfos.Remove(activityInfo); // Prepare the result and stop the waiting task. activityInfo.Result = new ActivityResult(resultCode, data); activityInfo.WaitHandle.Set(); } }