如何在Android中正确使用AsyncTask

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

那么代码应该如何?

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

根据AsyncTask ,其

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

所以如果你想在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(); 

创build你的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(); 

你为什么不想传递任何论据? 你应该解释…

这是通常的工作原理(例子):

  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文档