How to create a singleton Page for Navigation Page(Xamarin Forms)

RedBeans 1 Reputation point
2021-10-05T22:47:54.903+00:00

I am using Android Foreground service on my App.
When I kill the app and restart it, my MainPage is created again.

await Navigation.PushAsync(new MainPage(), true);

I want to only create one MainPage and use it.

I tried the following code but did not work.

public partial class LoginPage : ContentPage
{
    static Page instance;
            :
    private async void Login(string id, string pass)
    {
                :
        try
        {
                :
            if (instance == null)
            {
                instance = new MainPage();
                Console.WriteLine("create MainPage");
            }
            else
            {
                Console.WriteLine("MainPage is already created");
            }
            await Navigation.PushAsync(instance, true);
        }
        catch (Exception e)
        {
            await DisplayAlert("error", "unexpected error occured." + e.Message, "OK");
        }
        finally
        {
        }
            :

It shows
error
unexpected error occured. Page must not already have a parent.

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