StartActivityForResult | OnActivityResult Deprecated in Xamarin Android

Along with androidX support StartActivityForResult and OnActivityResult got dprecated inside Fragment. Here we can see the one of the alternate approach for this deprecated api's in xamarin android.

Below code snippet explains the handling the above mentioned deprecated API's:

In my previous post explained  Android Keystore based encryption and decryptionHow to implement Dependency injection in xamarin form using AutoFacReOrder the list items by drag and drop in xamarin androidCustom Image Gallery Control using Xamarin Form

-

using AndroidX.Activity.Result;
using AndroidX.Activity.Result.Contract;
[Activity(Label = "EditImageActivity", MainLauncher = false)]
public class MyActivity : Activity
{
private ActivityResultCallback _activityResultCallback;
private ActivityResultLauncher _activityResultLauncher;
public static int _requestCode;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
_activityResultCallback = new ActivityResultCallback(this);
_activityResultLauncher = RegisterForActivityResult(new ActivityResultContracts.StartActivityForResult(), _activityResultCallback);
}
private void OpenGallery()
{
//var galleryIntent =.. //create your intent
_requestCode = "1001"; //flag to handle the multiple intent request
_activityResultLauncher.Launch(galleryIntent);
}
public void MyActivityResultReceived( int resultCode, Intent data)
{
if ((_requestCode == "1001") || (resultCode == (int)Result.Ok))
{
//handle the result
}
}
class ActivityResultCallback : Java.Lang.Object, IActivityResultCallback
{
MyActivity _myActivity;
public ActivityResultCallback(NotesFragment myActivity)
{
_myActivity = myActivity; //initialise the parent activity/fragment here
}
public void OnActivityResult(Java.Lang.Object result)
{
var activityResult = result as ActivityResult;
_myActivity.MyActivityResultReceived(activityResult.ResultCode, activityResult.Data); //pass the OnActivityResult data to parent class
}
}
}
view raw MyActivity.cs hosted with ❤ by GitHub


Happy coding!!


5 comments:

  1. Hello,

    ActivityResultCallback class not found.
    However IActivityResultCallback interface exists
    Do I need to add any references?

    ReplyDelete
  2. OK. The class is there at the end of the code.
    Thanks

    ReplyDelete
  3. I'm upgrading one of my apps to android API 33 and I'm having some issues with this code that I can't resolve. The line " _activityResultLauncher = RegisterForActivityResult(new ActivityResultContracts.StartActivityForResult(), _activityResultCallback);" causes the IDE error "The name 'RegisterForActivityResult' does not exist in the current context". I'm using Visual Studio 2022 v17.3.6. I can't even test the code until I resolve this. Can anyone here help me?

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. Did you add required namespace, as suggested in this sample code

      Delete