异步任务由 3 个泛型类型(称为)和Params, Progress and Result
4 个步骤(称为onPreExecute
、doInBackground
和)定义。onProgressUpdate
onPostExecute
AsyncTask 的泛型类型:
异步任务使用的三种类型如下:
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.
并非所有类型都始终由异步任务使用。要将类型标记为未使用,只需使用类型 Void:
private class MyTask extends AsyncTask<Void, Void, Void> { ... }
AsyncTask 并实现了 4 个方法:
1. doInBackground:执行长时间运行的代码在这个方法中。当 onClick 方法在单击按钮时执行时,它会调用 execute 方法,该方法接受参数并自动调用 doInBackground 方法并传递参数。
2. onPostExecute:在doInBackground方法完成处理后调用该方法。doInBackground 的结果被传递给这个方法。
3. onPreExecute:在调用doInBackground方法之前调用该方法。
4. onProgressUpdate:这个方法是通过在doInBackground调用这个方法的任何时候调用publishProgress来调用的。
Overriding onPostExecute, onPreExecute and onProgressUpdate is optional.
要记住的要点:
1. Instance of Async Task needs to be created in UI thread. As shown in onClick method a new instance of LongOperation is created there. Also execute method with parameters should be called from UI thread.
2. Methods onPostExecute, onPreExecute and onProgressUpdate should not be explicitly called.
3. Task can be executed only once.
让我们看一个示例类 LongOperation,它扩展了下面的 AsyncTask:查看源打印?
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// perform long running operation operation
return null;
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPreExecute()
*/
@Override
protected void onPreExecute() {
// Things to be done before execution of long running operation.
//For example showing ProgessDialog
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onProgressUpdate(Progress[])
*/
@Override
protected void onProgressUpdate(Void... values) {
/* Things to be done while execution of long running operation
is in progress.
For example updating ProgessDialog */
}
}