如何在Android中正确使用AsyncTask

ome*_*erk 42 android android-asynctask

我不想将任何参数传递给doInBackgroundAsyncTask的方法.

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

Meh*_*sar 95

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

    }
}
Run Code Online (Sandbox Code Playgroud)


Nam*_*lay 17

根据AsyncTask,它的

 AsyncTask<Params, Progress, Result>
Run Code Online (Sandbox Code Playgroud)
  • Params,执行时发送给任务的参数类型.
  • 进度,后台计算期间发布的进度单元的类型.
  • 结果,后台计算结果的类型.

因此,如果你想在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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

称之为:

 new DownloadLink().execute();
Run Code Online (Sandbox Code Playgroud)


ρяσ*_*я K 9

创建您的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) {                           

          }
    }
Run Code Online (Sandbox Code Playgroud)

并启动AsyncTask而不传递任何参数来执行:

   LongOperation longOperation = new LongOperation(this);
   longOperation.execute();
Run Code Online (Sandbox Code Playgroud)


Ole*_*ich 8

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

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

 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");
     }
 }
Run Code Online (Sandbox Code Playgroud)

要执行它,你打电话:

new DownloadFilesTask().execute(url1, url2, url3);
Run Code Online (Sandbox Code Playgroud)

来源:Android文档