Search code examples
android.netmauiandroidxmaui-blazor

Maui Android CredentialManager context problem


I am trying to create a .NET MAUI Wrapper around AndroidX.credentials and I am trying to use it in my Maui Blazor app.

When I want to call _credentialManager.CreateCredentialAsync like:

_credentialManager.CreateCredentialAsync(
    act,
    request,
    null,
    ContextCompat.GetMainExecutor(act),
    callback
);

I get an error

"Failed to launch the selector UI. Hint: ensure the context parameter is an Activity-based context."

I have tried several different ways how to obtain the context:

var context1 = Platform.AppContext;//1
var context2 = Platform.CurrentActivity.BaseContext;//2
var context3 = Platform.CurrentActivity?.ApplicationContext;//1
var context4 = Application.Current?.Handler?.MauiContext?.Context;//1

but none of them work. Is there a different way how to obtain the correct context ? Or is there a different problem ?


PS: This call works on my Pixel6(api34), but doesnt work on my simulator with Pixel4(api33) nor on my SamsungS9(api29). Based on doc this method should be available.


Solution

  • The issue you encountered with the _credentialManager.CreateCredentialAsync() method stems from the necessity of providing a context parameter that is based on an Activity.

    In Maui, to obtain the current Activity instance, you can use the following code:

      Android.Content.Context context = Platform.CurrentActivity; 
    

    This method returns the current running Activity, allowing you to pass it as a context parameter to relevant APIs.