【问题标题】:How to use AsyncTask correctly in Android [closed]如何在 Android 中正确使用 AsyncTask [关闭]
【发布时间】:2012-12-24 10:20:52
【问题描述】:

我不想将任何参数传递给 AsyncTask 的 doInBackground 方法。

那么代码应该是什么样的?

【问题讨论】:

  • 在发布内容之前先尝试一下...阅读博客和开发者指南
  • 你必须阅读......click here

标签: android android-asynctask


【解决方案1】:
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;

public class AsyncExample extends Activity{


private String url="http://www.google.co.in";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}


@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();

    new AsyncCaller().execute();

}

private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
    ProgressDialog pdLoading = new ProgressDialog(AsyncExample.this);

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.show();
    }
    @Override
    protected Void doInBackground(Void... params) {

        //this method will be running on background thread so don't update UI frome here
        //do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here


        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        //this method will be running on UI thread

        pdLoading.dismiss();
    }

    }
}

【讨论】:

  • 谢谢!这看起来像我想要的......:D
【解决方案2】:

根据AsyncTask,其

 AsyncTask<Params, Progress, Result>
  • Params,执行时发送给任务的参数类型。
  • 进度,进度单位在期间发布的类型 后台计算。
  • Result,后台计算结果的类型。

所以如果你想在 doInBackground 中传递 void,只需传递 void 来代替 Params。

示例代码:

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


        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub

            //Do Your stuff here..
            return null;
        }
    }

并将其称为:

 new DownloadLink().execute();

【讨论】:

  • 表示params是任务数组,所有任务的返回类型都是void
  • @blackHawk - 是的
【解决方案3】:

创建您的 AsyncTask 类,就好像您不想将任何参数传递给 doInBackground 一样:

 public class LongOperation extends AsyncTask<Void, Void, String> {


          public LongOperation(Context context) {

          }

          @Override
          protected void onPreExecute() {

          }

          @Override
          protected String doInBackground(Void... params) {

              return null;
          }      

          @Override
          protected void onPostExecute(String result) {                           

          }
    }

并在不传递任何参数的情况下启动 AsyncTask :

   LongOperation longOperation = new LongOperation(this);
   longOperation.execute();

【讨论】:

  • 我注意到 Android Studio 自动完成不会给你“”,这可能会让你绊倒。另外,请注意doInBackground 的返回值确实必须是类的第三个参数(所示示例中的“String”)。
【解决方案4】:

你为什么不想给它传递任何参数呢?你应该解释...

这是它通常的工作方式(示例):

 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");
     }
 }

然后调用它来执行它:

new DownloadFilesTask().execute(url1, url2, url3);

来源:Android docs

【讨论】:

  • 通常,参数传递给AsyncTask但不是必须的
  • 我不需要将参数传递给 doInBakground 。此方法仅通过 POST 方法在我的 Web 服务器上打开一个 php 文件。我只需要从那个 php 文件中得到响应。所以我不需要将任何参数传递给doInBackground
  • 简单 - 您只需使用 Void 类。所以你会有private class DownloadFilesTask extends AsyncTask&lt;Void, Integer, Long&gt; {
猜你喜欢
  • 2021-02-15
  • 1970-01-01
  • 1970-01-01
  • 2012-10-08
  • 1970-01-01
  • 2011-11-22
  • 2015-05-12
  • 2012-11-19
相关资源
最近更新 更多