由于访问网络等耗时的操作都要写在子线程中,每次都用new Thread()方法的话比较麻烦,这时可以用异步任务的方法访问网络:
private class MyHttpTask extends AsyncTask<Params, Progress, Result>{
其中,Params是传递的参数类型,Progress是下载相关的进度提示,Result是服务器回复结果的封装。
创建异步任务AsyncTask的顺序是:
①
onPreExecute():
Runs on the UI thread before doInBackground(Params...)
.
② doInBackground(Params... params): Override this method to perform a computation on a background thread.
③
onPostExecute(Result result):
Runs on the UI thread after doInBackground(Params...)
.
方法③的参数是方法②执行后返回的结果,方法③主要就是执行异步任务后更新界面。
执行时用execute方法,由于父类中的execute方法是final类型的,不能重写,我们可以复制父类中的该方法,改写方法名,再在里面调用父类的execute方法:
public final AsyncTask<Integer, Void, Message> executeProxy(Integer... params) {
if(NetUtil.checkNet(context)){
return super.execute(params);
}else{
PromptManager.showNoNetWork(context);
}
return null;
}
其中params是要传递的参数。可以把执行异步任务的方法抽取到BaseUI中。之所以这样写,是可以省略掉访问网络的判断。
}