【问题标题】:android how to work with asynctasks progressdialogandroid如何使用asynctasks进度对话框
【发布时间】:2011-06-23 06:44:41
【问题描述】:

Asynctask 有 4 个覆盖方法onPreExecute()doInBackground()onProgressUpdate()onPostExecute() 除了onProgressUpdate 之外,所有的都在工作。 我应该怎么做才能使 onProgressUpdate() 起作用。 谁能简单解释一下onProgressUpdate()有什么用,里面应该写什么?

【问题讨论】:

  • progressDialog.setIndeterminate(false); 如果你给了true

标签: android


【解决方案1】:

onProgressUpdate()用于通过该方法操作异步操作的进度。注意数据类型为Integer 的参数。这对应于类定义中的第二个参数。可以通过调用publishProgress()doInBackground() 方法的主体内触发此回调。

示例

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AsyncTaskExample extends Activity {

    protected TextView _percentField;

    protected Button _cancelButton;

    protected InitTask _initTask;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        _percentField = (TextView) findViewById(R.id.percent_field);
        _cancelButton = (Button) findViewById(R.id.cancel_button);
        _cancelButton.setOnClickListener(new CancelButtonListener());
        _initTask = new InitTask();
        _initTask.execute(this);
    }

    protected class CancelButtonListener implements View.OnClickListener {

        public void onClick(View v) {
            _initTask.cancel(true);
        }
    }

    /**
     * sub-class of AsyncTask
     */
    protected class InitTask extends AsyncTask<Context, Integer, String> {

        // -- run intensive processes here
        // -- notice that the datatype of the first param in the class definition matches the param passed to this
        // method
        // -- and that the datatype of the last param in the class definition matches the return type of this method
        @Override
        protected String doInBackground(Context... params) {
            // -- on every iteration
            // -- runs a while loop that causes the thread to sleep for 50 milliseconds
            // -- publishes the progress - calls the onProgressUpdate handler defined below
            // -- and increments the counter variable i by one
            int i = 0;
            while (i <= 50) {
                try {
                    Thread.sleep(50);
                    publishProgress(i);
                    i++;
                }
                catch (Exception e) {
                    Log.i("makemachine", e.getMessage());
                }
            }
            return "COMPLETE!";
        }

        // -- gets called just before thread begins
        @Override
        protected void onPreExecute() {
            Log.i("makemachine", "onPreExecute()");
            super.onPreExecute();
        }

        // -- called from the publish progress
        // -- notice that the datatype of the second param gets passed to this method
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            Log.i("makemachine", "onProgressUpdate(): " + String.valueOf(values[0]));
            _percentField.setText((values[0] * 2) + "%");
            _percentField.setTextSize(values[0]);
        }

        // -- called if the cancel button is pressed
        @Override
        protected void onCancelled() {
            super.onCancelled();
            Log.i("makemachine", "onCancelled()");
            _percentField.setText("Cancelled!");
            _percentField.setTextColor(0xFFFF0000);
        }

        // -- called as soon as doInBackground method completes
        // -- notice that the third param gets passed to this method
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Log.i("makemachine", "onPostExecute(): " + result);
            _percentField.setText(result);
            _percentField.setTextColor(0xFF69adea);
            _cancelButton.setVisibility(View.INVISIBLE);
        }
    }
}

【讨论】:

  • 我想在特定时间出现 dilog。如果需要更多时间,我想发出警报。那么我会在哪里发出警报?
  • 在 onProgressUpdate() 中,超级方法不接受整数值作为参数。它只接受 Void
【解决方案2】:

四个步骤

当一个异步任务被执行时,任务会经过4个步骤:

onPreExecute(), 在执行任务之前在 UI 线程上调用。此步骤通常用于设置任务,例如通过在用户界面中显示进度条。

doInBackground(Params...), 在 onPreExecute() 完成执行后立即在后台线程上调用。此步骤用于执行可能需要很长时间的后台计算。异步任务的参数传递到这一步。计算的结果必须由这一步返回,并将传递回最后一步。此步骤还可以使用 publishProgress(Progress...) 来发布一个或多个进度单位。这些值在 UI 线程的 onProgressUpdate(Progress...) 步骤中发布。

onProgressUpdate(Progress...), 在调用 publishProgress(Progress...) 后在 UI 线程上调用。执行的时间是不确定的。此方法用于在后台计算仍在执行时在用户界面中显示任何形式的进度。例如,它可用于动画进度条或在文本字段中显示日志。

onPostExecute(Result), 在后台计算完成后在 UI 线程上调用。后台计算的结果作为参数传递给这一步。

示例

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
         // Escape early if cancel() is called
         if (isCancelled()) break;
     }
     return totalSize;
 }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
 }
}

AsyncTask 的泛型类型 异步任务使用的三种类型如下:

Params,执行时发送给任务的参数类型。

进度,在后台计算期间发布的进度单元的类型。

Result,后台计算结果的类型。

【讨论】:

【解决方案3】:

是的,你是对的,AsyncTask中有四种方法

当一个异步任务被执行时,任务会经过4个步骤:

onPreExecute()

在任务执行后立即在 UI 线程 上调用。此步骤通常用于设置任务,例如通过在用户界面中显示进度条。

doInBackground(Params...) 

onPreExecute() 完成执行后立即在后台线程上调用。此步骤用于执行可能需要很长时间的后台计算。异步任务的参数传递到这一步。计算的结果必须由这一步返回,并将传递回最后一步。此步骤也可以使用publishProgress(Progress...) 发布一个或多个单位的进度。这些值在 UI 线程上发布,在 onProgressUpdate(Progress...) 步骤中。

onProgressUpdate(Progress...)

在调用publishProgress(Progress...) 后在UI 线程 上调用。执行的时间是不确定的。此方法用于在后台计算仍在执行时在用户界面中显示任何形式的进度。例如,它可用于动画进度条或在文本字段中显示日志。

onPostExecute(Result)

在后台计算完成后在 UI 线程 上调用。后台计算的结果作为参数传递给这一步。

欲了解更多信息click here

【讨论】:

    【解决方案4】:

    onProgressUpdate 在调用publishProgress 后在 UI 线程上运行。从 AsyncTask 文档 - 你的代码应该是这样的

    private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
        protected Long doInBackground(URL... urls) {
            int count = urls.length;
            long totalSize = 0;
            for (int i = 0; i < count; i++) {
                totalSize += Downloader.downloadFile(urls[i]);
                publishProgress((int) ((i / (float) count) * 100));
            }
            return totalSize;
        }
    
        protected void onProgressUpdate(Integer... progress) {
            setProgressPercent(progress[0]);
        }
    
        protected void onPostExecute(Long result) {
            showDialog("Downloaded " + result + " bytes");
        }
    }
    

    【讨论】:

      【解决方案5】:
      hey this might help you??
      

      收到回复后进度条会自动消失

      User_AsyncTaskk extends AsyncTask
       public class User_AsyncTask extends AsyncTask<String, String, String>
          {
              String response = "";
      
              @Override
              protected void onPreExecute()
              {
                  try
                  {
                      if (progressDialog != null)
                          progressDialog.cancel();
                  }
                  catch (Exception e)
                  {
      
                  }
                  progressDialog = ProgressDialog.show(DisplayDetails.this, "", "Please wait...", true, true);
                  progressDialog.setCancelable(false);
                  progressDialog.show();
              }
      
      
       protected String doInBackground(String... params)
              {
      
                  try
                  {
      
      
                     //Complete ur Code
      
                      Log.i("AUTO ", "response  is : " + response);
                      return response;
                  }
      
                  catch (Exception e)
                  {
      
                  }
              }
      
       @Override
              protected void onPostExecute(String s)
              {
                  if (progressDialog != null) {
                      progressDialog.dismiss();
                      progressDialog = null;
                  }
      
                  try {
      
      
      
                  }
                  catch (Exception e)
                  {
      
                  }
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-26
        • 1970-01-01
        • 2014-04-27
        相关资源
        最近更新 更多