什么参数传入AsyncTask <arg1,arg2,arg3>?

我不明白我应该把什么放在这里,以及这些争论最终在哪里? 我究竟应该放什么,到底要去哪里? 我是否需要包括所有3个,还是可以包含1,2,20?

谷歌的Android文档说:

asynchronous任务由3个genericstypes定义,称为Params,Progress和Result,以及4个步骤,分别称为onPreExecute,doInBackground,onProgressUpdate和onPostExecute。

AsyncTask的genericstypes:

asynchronous任务使用的三种types如下:

Params, the type of the parameters sent to the task upon execution. Progress, the type of the progress units published during the background computation. Result, the type of the result of the background computation. 

并非所有types总是由asynchronous任务使用。 要将某个types标记为未使用,只需使用typesVoid:

  private class MyTask extends AsyncTask<Void, Void, Void> { ... } 

你可以进一步参考: http : //developer.android.com/reference/android/os/AsyncTask.html

或者你可以通过引用Sankar-Ganesh的博客来明确AsyncTask的作用

那么典型的AsyncTask类的结构如下所示:

 private class MyTask extends AsyncTask<X, Y, Z> protected void onPreExecute(){ } 

在启动新线程之前执行此方法。 没有input/输出值,所以只是初始化variables或任何你认为你需要做的事情。

  protected Z doInBackground(X...x){ } 

AsyncTask类中最重要的方法。 你必须把所有你想做的东西放在后台,在与主要的不同的线程中。 在这里我们有一个types为“X”的对象数组作为input值(你在头文件中看到了什么?我们有“… extends AsyncTask”这些是input参数的types)并返回一个types的对象“Z”。

  protected void onProgressUpdate(Y y){ } 

使用publishProgress(y)方法调用此方法,通常在您想要在主屏幕中显示任何进度或信息时使用此方法,如显示您在后台执行的操作进度的进度条。

  protected void onPostExecute(Z z){ } 

这个方法在后台操作完成后调用。 作为input参数,您将收到doInBackground方法的输出参数。

那么X,Y和Ztypes呢?

从以上结构可以推断出:

  X – The type of the input variables value you want to set to the background process. This can be an array of objects. Y – The type of the objects you are going to enter in the onProgressUpdate method. Z – The type of the result from the operations you have done in the background process. 

我们如何从外部课堂调用这个任务? 只是以下两行:

 MyTask myTask = new MyTask(); myTask.execute(x); 

其中x是typesX的input参数。

一旦我们的任务运行,我们就可以从“外部”中find它的状态。 使用“getStatus()”方法。

  myTask.getStatus(); 

我们可以收到以下状态:

正在运行 – 表示任务正在运行。

PENDING – 表示该任务尚未执行。

完成 – 表示onPostExecute(Z)已完成。

有关使用AsyncTask的提示

  1. 不要手动调用PreExecute,doInBackground和onPostExecute方法。 这是由系统自动完成的。

  2. 您不能在另一个AsyncTask或Thread中调用AsyncTask。 方法执行的调用必须在UI线程中完成。

  3. onPostExecute方法在UI线程中执行(在这里你可以调用另一个AsyncTask!)。

  4. 任务的input参数可以是一个Object数组,这样你可以放置任何你想要的对象和types。

请参阅以下链接:

  1. http://developer.android.com/reference/android/os/AsyncTask.html
  2. http://labs.makemachine.net/2010/05/android-asynctask-example/

如果您只想传递1个参数,则不能传递三个以上的参数,而对另外两个参数使用void。

 1. private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> 2. protected class InitTask extends AsyncTask<Context, Integer, Integer> 

asynchronous任务由在后台线程上运行的计算定义,其结果在UI线程上发布。 asynchronous任务由3个genericstypes定义,称为Params,Progress和Result,以及4个步骤,分别称为onPreExecute,doInBackground,onProgressUpdate和onPostExecute。

KPBird