【问题标题】:Operation AsyncTask操作异步任务
【发布时间】:2014-11-20 20:51:13
【问题描述】:

我不太清楚 'AsyncTask 的功能。

我正在尝试在 ProgressDialog 中放置一个按钮来取消 AsynkTask。

问题是当我调用方法时:runner.cancel(true); ProgressDialog 似乎消失了。但是 asynkTask 继续在后台工作。

我显示我的代码:

public class AsyncTaskRunner extends AsyncTask<String, String, String> {
        @Override
        protected void onCancelled(String result) {
            pDialog.dismiss();
            super.onCancelled(result);
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(context);

            pDialog.setCancelable(false);
            pDialog.setMessage(context.getResources().getString(
                    R.string.pDialog));
            if (codeLink == 2) {
                pDialog.setButton("cancel", new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        runner.cancel(true);

                    }
                });
            }

            pDialog.show();
        }
        @Override
        protected String doInBackground(String... params) {
        // Here download the data.
        }
        @Override
        protected void onPostExecute(String result) {
        //Here I make the parser.
        }
}

我的猜测:

可能是这样做的gate doInBackground()但是OnPostExecute()被执行了? 如果是烷氧基,我该如何擦除所有内容?还有 OnPostExecute() ??

【问题讨论】:

  • Asynctask 将使用方法“doInBackground”在后台工作,同时执行您想要显示的过程,在“onPreExecute”方法中显示它,当任务完成时,“onPostExecute”方法被命中。
  • @VibhorChopra 我正在尝试我无法理解的一切。你能解释得更好吗?
  • 你想在“doInBackground”方法中以json/xml形式下载一些数据并在“onpostexec”方法中解析这些数据吗???
  • @VibhorChopra 不是我的问题。我的问题是为什么当我删除 AsynkTask 时继续下载数据,然后是解析器。

标签: android android-asynctask


【解决方案1】:

AsyncTask 在后台工作。首先调用onPreExecute,然后调用doInBackground,然后在完成后台任务后,调用onPreExecute。

请继续检查doInBackground 中的isCancelled()。

 protected Object doInBackground(Object... x) {
    while (/* condition */) {
      // work...
      if (isCancelled()) break;
    }
    return null;
 }

【讨论】:

  • 告诉我一个错误“break不能在循环或开关之外使用”
  • 是的,不能在循环外使用,我这里用过循环。请检查您的代码,确保您使用了括号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多