显示 ProgressDialog 并在一段时间后调用 OnBackPressed()
Show ProgressDialog and call OnBackPressed() after certain period
ProgressDialog 应该显示 5 秒,然后 OnBackPressed() 应该执行。目前 ProgressDialog 从未出现在屏幕上。如果我将 OnBackPressed() 放在委托进度对话框中,则会显示,但我会收到错误消息,即 OnBackPressed() 应该从 MainThread 执行。我能做什么?
private async SomeAsyncMethod()
{
await ShowProgressDialog();
......
}
private Task ShowMessage()
{
var progressDialog = ProgressDialog.Show(this, "Bestandskorrektur", "Bestandskorrektur wird ausgeführt! Bite warten...", true);
new Thread(new ThreadStart(delegate
{
Thread.Sleep(5000);
RunOnUiThread(() => progressDialog.Hide());
OnBackPressed(); // Gives error.
})).Start();
return Task.CompletedTask;
}
更新:基于答案的解决方案:
var pd = ProgressDialog.Show(this, "Bestandskorrektur", "Bestandskorrektur wird ausgeführt! Bitte warten...", true);
var h = new Handler();
void action()
{
RunOnUiThread(() => pd.Hide());
OnBackPressed();
}
h.PostDelayed(action, 5000);
尝试使用如下所示的 Handler().postDelayed() -
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//hide progressbar
onBackPressed();
}
}, 5000);
onBackPressed() 应该从 UI 线程调用。 Darshan 建议的是正确答案。当您想从后台线程更新 UI 时(在本例中是等待计时器完成的线程),您应该使用 Handler。代替线程,替换
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//Do your work here
}
}, /*Delay in miliseconds*/ );
ProgressDialog 应该显示 5 秒,然后 OnBackPressed() 应该执行。目前 ProgressDialog 从未出现在屏幕上。如果我将 OnBackPressed() 放在委托进度对话框中,则会显示,但我会收到错误消息,即 OnBackPressed() 应该从 MainThread 执行。我能做什么?
private async SomeAsyncMethod()
{
await ShowProgressDialog();
......
}
private Task ShowMessage()
{
var progressDialog = ProgressDialog.Show(this, "Bestandskorrektur", "Bestandskorrektur wird ausgeführt! Bite warten...", true);
new Thread(new ThreadStart(delegate
{
Thread.Sleep(5000);
RunOnUiThread(() => progressDialog.Hide());
OnBackPressed(); // Gives error.
})).Start();
return Task.CompletedTask;
}
更新:基于答案的解决方案:
var pd = ProgressDialog.Show(this, "Bestandskorrektur", "Bestandskorrektur wird ausgeführt! Bitte warten...", true);
var h = new Handler();
void action()
{
RunOnUiThread(() => pd.Hide());
OnBackPressed();
}
h.PostDelayed(action, 5000);
尝试使用如下所示的 Handler().postDelayed() -
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//hide progressbar
onBackPressed();
}
}, 5000);
onBackPressed() 应该从 UI 线程调用。 Darshan 建议的是正确答案。当您想从后台线程更新 UI 时(在本例中是等待计时器完成的线程),您应该使用 Handler。代替线程,替换
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//Do your work here
}
}, /*Delay in miliseconds*/ );