android - 如何从后台关闭进度对话框

标签 android background-process progressdialog

我对 Android 有点陌生,陷入了一种不知道如何处理的情况。

这是我正在尝试做的事情:

从“Activity ”中,我启动一些任务并在任务在后台完成时显示进度对话框。 如果任务成功完成,我将关闭该 Activity 并启动新的 Activity 。

但是,如果在后台我捕获了一个异常,我想返回到 Activity 并关闭进度对话框并显示一个 Toast,也许发生了一些异常。

来自 Activity :

@Override
public void onCreate(Bundle savedInstanceState) 
{
 // my code

 // start Progress Dialog
   showProgressDialog();  
}

public void showProgressDialog()
{
   PD =  new ProgressDialog(getActivity());
   PD.setMessage("Downloading.....");
   PD.show();
}

@Override
public void onDestroy()
{
   super.onDestroy();
   if (PD != null) 
   {
      PD.dismiss();
      PD = null;
   }
}

在后台:

try 
{
   // perform some db tasks 
   // using AsyncTask 
}
catch (Exception e) 
{
   if(e.getErrorCode() == 34)
   {
      // From here I want go back to Activity and close the Progress dialog
      // and shows what error has occurred.
   }
}

那么,如果发生异常,我应该如何返回 Activity 并关闭进度对话框,或者还有其他方法可以做到这一点吗?

最佳答案

据我所知,ProgressDialog 位于您的 UI 线程中,并且您无法在后台线程中访问它。为什么不使用 AsyncTask 来代替呢?它易于使用,您可以更轻松地处理它。示例:

class TestAsync extends AsyncTask<Void, Void, Void> {

        private ProgressDialog mDialog;
        private Boolean error = false;

        @Override
        protected void onPreExecute() {

            mDialog = new ProgressDialog(TestActivity.this);
            mDialog.setCancelable(false);
            mDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {


            try {
                // whatever you would like to do in background
            } catch (Exception e) {
                error = true;
            }

            return null;
        }

        protected void onPostExecute(Void... arg0) {
            mDialog.dismiss();

            if (error) {
                Toast.makeText(getApplicationContext(),
                        R.string.error, Toast.LENGTH_SHORT).show();
                return;
            } else {

                // whatever you would like to do after background 
            } 

        }
    }

关于android - 如何从后台关闭进度对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25969262/

相关文章:

android - 如何构建或从哪里获得支持 Fortran 的 Android NDK 独立工具链?

android - ProgressDialog onCreate

android - 如何在 ProgressDialog 关闭后立即执行指令/方法?

android - ActionBarSherlock布局膨胀错误

c# - 在 Xamarin.android 中创建搜索函数来查询 Microsoft Azure 表记录

android - 操作栏按钮背景

ruby-on-rails - Rails : Segmentation fault at Rjb when in background process, 不在后台时工作正常吗?

ios - 在后台模式下定期向服务器发送小数据

bash - bash for 循环中的后台进程

android - 显示没有文本Android的进度对话框