AsyncTask类是什么
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
实例
private class MyTask extends AsyncTask<Integer, Integer, String> { ... }
AsyncTask内部的函数
public final AsyncTask<Params, Progress, Result> execute(Params... params)
void onPreExecute ()
Result doInBackground (Params... params)
void publishProgress (Progress... values)
void onPostExecute (Result result)
onPreExecute,publishProgress,onPostExecute是运行在主线程中,不能进行耗时操作。
execute函数有多个多态函数,这些多态函数可以满足其他各种需求
AsyncTask的使用
1,继承AsyncTask类
2,至少实现onPreExcute(),doInBackground(),publishProgress(),onPostExecute()
3,在主线程中获得AsyncTask子类的对象,调用exceute函数传递参数并激活AsyncTask的执行。
4,在google给的APIdemo中,AsyncTask通常作为成员变量直接在activity中定义并实现,以便在onPostExecute中把结果赋值给其他对象。
AsyncTask的参数
1,在继承AsyncTask时声明的三个对象Params,Progress,Result可以为空,如果为空,设置为void。
2,Params涉及到的地方有两处,在execute参数中传递,在doInBackground中通过Params[0].intValue或者Params[0].toString获得。
3,Params可以传递多个相同类型的参数,在execute中以多个参数的形式发出,在doInBackground中以数组的形式获得。
4,Progress涉及到的位置有两处,在doInBackground中以publishProgress的参数格式传递,在onProgressUpdate中以value[0]格式接收,同样可以传递多个参数,方式与Params中相同。最大的作用就是更新进度条了,所以这个参数经常会被设置为Integer。
5,Result则只能传递一个,涉及到的位置是doInBackground的返回值,onPostExecute的参数。