Search code examples
c#androidxamarin.androidmauistartactivityforresult

Can't find RegisterForActivityResult in Xamarin/Maui C# libraries?


I have a mobile app that was written in Xamarin Forms; I have ported it to MAUI as Xamarin Forms is going out of support.

Lately, I have been trying to add Bluetooth functionality to the app. The first part of this is asking the user for permission, and I'm trying to use the modern method with StartActivityForResult feeding into RegisterForActivityResult.

There's just one problem: I can't find RegisterForActivityResult anywhere in the Xamarin.Android/MAUI C# libraries. Googling has come up empty (except for Java/Kotlin code). Microsoft seems to have never heard of the method, except for one open issue in the Xamarin Android repository only tangentially referencing it.

{
    //ask for permission
    Intent btPermissionsDialog = new Intent(BluetoothAdapter.ActionRequestEnable);
    ActivityResultLauncher btPermsResult = /*Platform.CurrentActivity. ??*/ RegisterForActivityResult(new ActivityResultContracts.StartActivityForResult(), //???
        //RegisterForActivityResult isn't found??
    
    //eventually:
    Platform.CurrentActivity.StartActivityForResult(btPermissionsDialog, btPermsRequest);
}

This is what I have so far. Am I stuck using OnActivityResult? I was hoping to make the Bluetooth-handling class not tied to a specific activity, but this issue of the permissions box is not making it easy.


Solution

  • I can confirm that the answer was to cast Platform.CurrentActivity to an AndroidX.Activity.ComponentActivity (MAUI's MauiAppCompatActivity is an extension of ComponentActivity).