Search code examples
xamarin.formsnavigationcross-platformonresume

Xamarin Forms OnResume special processing


When my Xamarin Forms cross platform app resumes, I want to intercept the navigation and transfer to a loading page I have that checks to see if certain data has changed etc. After I perform this processing, if nothing has changed, I want to resume the navigation to the original page the onresume would have taken me to.

So to start with I have saved an instance of the page the check for changes in the data in a variable in my app.xaml.cs file. When my app starts, I created an instance of the page I want and navigate to it. Below is the code from my app.xaml.cs file:

            gobj_BaseLoadingPage = new baseloadingpage();

            if (Application.Current.MainPage == null)
            {
                Application.Current.MainPage = new NavigationPage(gobj_BaseLoadingPage);
            }

So now in the on resume, I want to go back to this loading page. I have tried many variations of the code below but I cannot seem to get it to work. With the code below, by base loading page is never displayed and the app simply goes back to the page it was on when it was suspended.

        App.Current.MainPage = (Page)gobj_BaseLoadingPage.Parent;
        gobj_BaseLoadingPage.Parent = null;
        Application.Current.MainPage.Navigation.PushAsync(gobj_BaseLoadingPage);

If I just do a pushasync with the page without clearing its parent I get an error that the page cannot already have a parent.

Any suggestions would be greatly appreciated.


Solution

  • Use PopToRootAsync, InsertPageBefore, and PopAsync. (Not showing any saving of state):

    Page rootPage;
    
    public App()
    {
      InitializeComponent();
    
      rootPage = new OriginalRootPage();
      MainPage = new NavigationPage(rootPage);
    }
    
    protected override async void OnResume()
    {
      // Handle when your app resumes
      Debug.WriteLine("Resume");
    
      var nav = MainPage.Navigation;
    
      // Pops all but the root Page off the navigation stack, 
      // making the root page of the application the active page.
      await nav.PopToRootAsync();
    
      if (!(nav.NavigationStack.First() is NewRootPage))
      {
        // Insert a page on the navigation stack before the original rootPage
        var newRootPage = new NewRootPage();
        nav.InsertPageBefore(newRootPage, rootPage);
    
        // Pops the original rootPage, making the newRootPage the only page on the stack
        await nav.PopAsync();
      }
    }