AsyncTask的使用:
new MyTask().execute(Params...params);
AsyncTask的三个泛型参数说明(三个参数可以是任何类型)
1. 第一个参数Params:传入doInBackground()方法的参数类型
2. 第二个参数Progress:传入onProgressUpdate()方法的参数类型
3. 第三个参数Result:传入onPostExecute()方法的参数类型,也是doInBackground()方法返回的类型
private class MyTask extends AsyncTask<Params, Progress, Result> {
/*
* Runs on the UI thread before doInBackground(Params...)
*/
protected void onPreExecute (){
...
}
/*
* Override this method to perform a computation on a background thread.
* The specified parameters are the parameters passed to execute(Params...)
* by the caller of this task.This method can call publishProgress(Progress...)
* to publish updates on the UI thread.
*/
protected Result doInBackground (Params... params){
...
}
/*
* Runs on the UI thread after doInBackground(Params...).
* The specified result is the value returned by doInBackground(Params...).
* This method won't be invoked if the task was cancelled.
* Parameters result:The result of the operation computed by doInBackground(Params...).
*/
protected void onPostExecute (Result result){
...
}
/*
* Runs on the UI thread after publishProgress(Progress...) is invoked.
* The specified values are the values passed to publishProgress(Progress...).
*/
protected void onProgressUpdate (Progress... values) {
...
}
/*
* This method can be invoked from doInBackground(Params...) to publish updates
* on the UI thread while the background computation is still running.
* Each call to this method will trigger the execution of
* onProgressUpdate(Progress...) on the UI thread. onProgressUpdate(Progress...)
* will not be called if the task has been canceled.
*/
protected final void publishProgress (Progress... values) {
...
}
/*
* Runs on the UI thread after cancel(boolean) is invoked and doInBackground(Object[])
* has finished.The default implementation simply invokes onCancelled()
* and ignores the result.If you write your own implementation,
* do not call super.onCancelled(result).
*/
protected void onCancelled (Result result) {
...
}
}