Robert Achmann
Robert Achmann

Reputation: 2045

How to restart the application using Xamarin.Forms

If I manage a session (any concept of a session is suitable) in my app, and I deem that the session has expired, for whatever reason, how do I programmatically restart the application, universally for iOS, Android, WinPhone?

Upvotes: 5

Views: 13253

Answers (6)

FrankLinTw
FrankLinTw

Reputation: 71

New Instance of MainPage is useful to me. (for Xamarin.Forms)

Device.BeginInvokeOnMainThread(() =>
{
    App.Current.MainPage = new AppShell();
});

Upvotes: 0

Nick Kovalsky
Nick Kovalsky

Reputation: 6492

You cannot restart a maui app, instead you can

  1. set new culture info etc
  2. reinitialize needed services
  3. set a newly created MainPage, consuming the new context

Upvotes: 0

chrisbyte
chrisbyte

Reputation: 1633

For what it is worth; I am using the Blazor Xamarin setup (Hybrid application, I think it is now .Net MAUI) and this is what I am doing to reload the Desktop application, based on other answers and suggestions in this post.

App.cs

public class App : Xamarin.Forms.Application
{
    private static IHost _host;

    public App()
    {
        // ... hostBuilder stuff. Configure services, etc.

        _host = hostBuilder.Build();

        Reload();
    }

    public static void Reload()
    {
        Current.MainPage = new ContentPage();
        NavigationPage.SetHasNavigationBar(Current.MainPage, false);
        _host.AddComponent<Main>(parent: Current.MainPage);
    }
}

App.razor

I keep this in the main App.razor called using a button. The idea is to use it if there is an error that bubbles up to the top and needs to reload the application.

@* Show button if there is an error *@
<button class="btn btn-sm btn-danger" @onclick="Reload">Reload</button>

@code {
    void Reload()
    {
        Application.Current.MainPage.Dispatcher.BeginInvokeOnMainThread(() => 
        {
            MyHybridApplication.App.Reload();
        });
    }
}

Upvotes: 1

mdimai666
mdimai666

Reputation: 787

new instance of MainPage

to call from anywhere. If just create from async will not work

void Reset()//require in the main Thread, also the app will crash
{
    (App.Current as App).MainPage.Dispatcher.Dispatch(() =>
    {
        (App.Current as App).MainPage = new AppShell();
    });
}

Upvotes: 3

Jordi Prat
Jordi Prat

Reputation: 141

You can create a new instance of MainPage

(Application.Current).MainPage = new NavigationPage(new MainPage());

Upvotes: 6

Jason
Jason

Reputation: 89169

You can't explicitly restart an App - iOS specifically prohibits this, and there is no universal mechanism to do this on other platforms. If you determine that the session has expired, you will need to prompt the user to login, and do any initialization manually.

Upvotes: 6

Related Questions