显示ProgressDialog并在一段时间后调用OnBackPressed()

问题描述 投票:0回答:2

ProgressDialog应显示5秒,然后执行OnBackPressed()。目前ProgressDialog从未出现在屏幕上。如果我将OnBackPressed()放在委托进度对话框中,但是我得到错误,应该从MainThread执行OnBackPressed()。我能做什么?

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);
android android-asynctask xamarin.android progressdialog
2个回答
2
投票

尝试使用Handler()。postDelayed()如下所示 -

new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //hide progressbar
                        onBackPressed();
                    }
                }, 5000);

1
投票

应该从UI线程调用onBackPressed()。 Darshan建议的是正确的答案。如果要从后台线程更新UI(在本例中是等待计时器完成的线程),则应使用Handler。代替线程,替换

new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //Do your work here

                    }
                }, /*Delay in miliseconds*/ );
© www.soinside.com 2019 - 2024. All rights reserved.