我有一个其中具有异步方法的 Activity 。此异步方法可以长时间运行。返回异步方法后,需要更新UI,并且某些控件引用了该 Activity 。
目前,如果在异步任务运行时未进行任何配置更改(例如屏幕旋转),则一切正常。但是,如果配置更改在运行时发生,则抛出 Activity 被破坏的异常,并且不会更新UI。从我所做的阅读来看,这似乎是因为async方法捕获了上下文,然后尝试更新旧的上下文,该上下文当然在配置更改后被破坏了。
我的问题是:解决此问题的最佳方法是什么?在最坏的情况下,解决该问题的方法是什么?
最佳答案
我个人认为您只有三种选择
要永久禁用它,请设置ConfigurationChanges
[Activity(Label = "...", ConfigurationChanges = Android.Content.PM.ConfigChanges.KeyboardHidden | Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
要在任务运行时将其暂时禁用,您应该禁用轮播处理,
禁用
this.RequestedOrientation = Android.Content.PM.ScreenOrientation.Nosensor;
使能
this.RequestedOrientation = Android.Content.PM.ScreenOrientation.Sensor;
RetainInstance = true
防止片段破坏。那可能行得通,但我从未测试过。 CancelationToken
取消任务,然后以OnRestoreInstanceState()
重新启动它这是如何取消任务的示例
{CancellationTokenSource cts;...// If a download process is already underway, cancel it.if (cts != null){ cts.Cancel();}
// Now set cts to cancel the current process if the button is chosen again.CancellationTokenSource newCTS = new CancellationTokenSource();cts = newCTS;
try{ //Send cts.Token to carry the message if there is a cancellation request. await AccessTheWebAsync(cts.Token);}// Catch cancellations separately.catch (OperationCanceledException){ ResultsTextBox.Text += "\r\nDownloads canceled.\r\n";}catch (Exception){ ResultsTextBox.Text += "\r\nDownloads failed.\r\n";}// When the process is complete, signal that another process can proceed.if (cts == newCTS) cts = null;}
而在任务中
async Task AccessTheWebAsync(CancellationToken ct)
{
...
// Retrieve the website contents from the HttpResponseMessage.
byte[] urlContents = await response.Content.ReadAsByteArrayAsync();
// Check for cancellations before displaying information about the
// latest site.
ct.ThrowIfCancellationRequested();
...
}
关于xamarin - 处理异步方法的配置更改,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25027276/