How to close browser tab with Xamarin.Android?

Jonas Rembratt 1 Reputation point
2022-05-18T08:20:14.857+00:00

So, I wrote a Nuget that allows dev in my company to quickly setup authorization using OIDC. Part of that, of course, is handing off the authentication step to a browser so I'm simply invoking Browse.OpenAsync with LaunchMode = BrowserLaunchMode.SystemPreferred. I also set up a HTTP listener that awaits the ahtority's authorization code callback. All works find but the browser window is of course still sitting at the top, hiding the initiating app. I do realise I can use deep linking to simply "call up" the app again but that has two implications I would like to avoid: The need to register schema uri with the mobile OS and, above all, the need to register that (weird) callback URI with my company's API management system (which doesn't like anything but "http" or "https" URL schemes. Those requirements makes it more complicated for our devs to get started and, like I mentioned, it doesn't work very well with our API management system, so I'm looking for a simpler solution.

I have solved this for iOS by simply fetching the key window's view controller and dismissing it, like so:

async Task<Outcome> IPlatformService.TryCloseTopWindowAsync(bool isModalWindow, bool animated)
{
    var window = UIApplication.SharedApplication.KeyWindow;
    var viewController = window?.RootViewController;
    if (viewController is null)
        return Outcome.Fail("Couldn't obtain top window view controller");

    try
    {
        if (isModalWindow)
        {
            viewController.DismissModalViewController(animated);
            return Outcome.Success();
        }
        await viewController.DismissViewControllerAsync(animated);
            return Outcome.Success();
    }
    catch (Exception ex)
    {
        return Outcome.Fail(ex);
    }
}

Unfortunately, I'm not very good with Android's (Java based) APIs so I'm wondering if it's possible to do something similar here? Can I get the top app (activated by my own app) and dismiss it? If so; how?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,291 questions
{count} votes