【问题标题】:Background operation and ProgressDialog后台操作和 ProgressDialog
【发布时间】:2011-06-01 18:59:11
【问题描述】:

我创建了一个AsyncTask 来执行我的后台操作。 UI 显示ProgressDialog。我将Context 传递给AsyncTask 的构造函数。

当我想从AsyncTask 操作ProgressDialog 文本时会出错,因为ProgressDialog 框是由不同的线程创建的。

关于如何使AsyncTaskProgressDialog 框进行通信的提示或想法,或者创建ProgressDialog 框的更好方法?

【问题讨论】:

    标签: android progressdialog android-asynctask


    【解决方案1】:

    您不应通过 AsyncTaskdoInBackground 函数与 UI 进行通信。请改用onProgressUpdate 函数。

    private class BackgrounTask extends AsyncTask<Integer, Integer, Integer> {
    
        protected Integer doInBackground(Integer... count){
           int max = count[0];
           for (int i = 0; i < count; i++) {
             publishProgress(i, max);
           }
           return max;
        }
    
        protected void onProgressUpdate(Integer... progress) {
           int cur = progress[0];
           int max = progress[1];
    
           //update your progress dialog here
        }
    
        protected void onPostExecute(Integer result) {
           //process result
        }
    }
    

    【讨论】:

    • 得到它的工作,感谢您的问题编辑和遮阳篷!
    【解决方案2】:

    使用AsyncTask.publishProgress() 方法并覆盖AsyncTask.onProgressUpdate() 方法。在此方法中更新您的进度对话框。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-28
      相关资源
      最近更新 更多