How to restart the application using Xamarin.Forms

12.8k views Asked by At

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?

6

There are 6 answers

0
Jason On BEST ANSWER

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.

0
FrankLinTw On

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

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

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();
    });
}
1
Jordi Prat On

You can create a new instance of MainPage

(Application.Current).MainPage = new NavigationPage(new MainPage());
0
chrisbyte On

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();
        });
    }
}
0
Nick Kovalsky On

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