App resuming results in crash with FormsAppCompatActivity

后端 未结 2 1433
暗喜
暗喜 2021-01-18 10:01

I have a Xamarin Forms app, currently being built for Android. I have a MainActivity that used to extend FormsApplicationActivity, but because I wa

相关标签:
2条回答
  • 2021-01-18 10:12

    I had the similiar issue. There are few points about it:

    1) Move your MainPage setting code to App constructor. As MainPage should be set in OnCreate method.

    public App () {
        MainPage = isRegistered 
                    ? new NavigationPage(new LoginPage()) 
                    : new NavigationPage(new RegisterPage()); 
    }
    

    2) You need to set you root page before OnCreate finishes. As you do not know the page you need, you may just set blanc page.

    public App () {
         MainPage = new ContentPage();
    }
    

    3) If this does not help. You can simply add try/catch block abound MainPage setter. This is dirty solution, but it works. In AppCompatActivity xamarin uses Fragments not Views. The crash happens, when android tries to restore fragment state. On plain android we used to use CommitAllowingStateLoss().

    try{
           MainPage = isRegistered 
                ? new NavigationPage(new LoginPage()) 
                : new NavigationPage(new RegisterPage()); 
    }catch(Exception){}
    
    0 讨论(0)
  • 2021-01-18 10:33

    I solved it by adding a thread sleep in my OnResume method before setting the MainPage. My OnResume now looks like this:

    protected override void OnResume()
    {
        base.OnResume();
    
        Task.Delay(10).Wait();
    
        bool isRegistered = _authenticationService.IsRegistered();
    
        MainPage = isRegistered 
            ? new NavigationPage(new LoginPage()) 
            : new NavigationPage(new RegisterPage());
    }
    

    See this bug report for this workaround.

    0 讨论(0)
提交回复
热议问题