当我的应用程序启动时,会设置一个启动画面,它只是一个ActivityIndicator
. 然后,运行一个启动服务并查找保存的密码的任务。此任务是异步运行的,因此ActivityIndicator
可以旋转。除非在此任务运行时按下主页按钮(Android),否则这可以正常工作。我知道这是因为如果应用程序关闭,则无法访问主线程。但我不知道如何解决这个问题。我将在下面发布 App.xaml.cs。
public App()
{
InitializeComponent();
MainPage = new SplashScreen();
app = this;
}
protected override async void OnStart()
{
base.OnStart();
await StartupAsync();
}
private async Task StartupAsync()
{
ServiceRegistrator.Startup();
MessagingCenter.Subscribe<NavigationMenuMasterDetailPage>(this, MessagingServiceConstants.LOGOUT, (sender) =>
{
Logout();
});
var assemblyType = typeof(App).GetTypeInfo();
AutoFac.Builder.RegisterAssemblyTypes(assemblyType.Assembly)
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces()
.SingleInstance();
_keyChainHelper = AutoFac.Container.Resolve<IKeyChainHelper>();
TextResources.Culture = DependencyService.Get<ILocalize>().GetCurrentCultureInfo();
var hasCredentials = HasKeyInChainstore("username") && HasKeyInChainstore("password");
if (hasCredentials)
{
await Task.Run(() =>
{
var logonService = AutoFac.Container.Resolve<ILogonService>();
var username = _keyChainHelper.GetKey("username");
var password = _keyChainHelper.GetKey("password");
logonService.Logon(username, password);
});
Device.BeginInvokeOnMainThread(() =>
{
MainPage = new NavigationMenuMasterDetailPage();
});
}
else
{
Device.BeginInvokeOnMainThread(() =>
{
ShowLoginPage();
});
}
}
我知道必须做一些事情来等待主线程可用,或者强制应用程序再次打开。确切的例外是“java.lang.IllegalStateException:在 onSaveInstanceState 之后无法执行此操作”,这发生在Device.BeginInvokeOnMainThread()
.