首先,本例子是本人项目一个登录模块中的一小片代码段,并不是完整的代码。只是单纯说明了继承于AsyncTask类的子类对象中各个方法的执行先后顺序。
本例在UI中有以下语句:AnsLogin ansk=new AnsLogin();ansk.execute("");是对AnsLogin类的使用。
/*
* 生成该类的对象,并调用其execute()方法之后(AnsLogin ansk=new AnsLogin();ansk.execute("");)* 首先执行onPreExecute()方法
* 其次是执行doInBackground()方法
*/
class AnsLogin extends AsyncTask<String, Integer, Integer> {
@Override
// 该方法将在执行实际的后台操作前被UI thread调用(也就是前面所说的:调用其execute()方法之后,首先执行onPreExecute()方法),其运行在UI线程当中。
//主要用于在异步操作之前做一些准备工作,如在页面出现转菊花提示:正在下载数据等
protected void onPreExecute() {
super.onPreExecute();
}
// 这里将主要负责执行那些很耗时的后台计算工作,如请求服务器参数等。
// 在该方法中,每次通过调用方法:publishProgress(i),都可以触发onProgressUpdate()方法
//doInBackground(String... params)的参数为UI线程中调用execute()方法时所传递过来的参数,如本例中ansk.execute("")就传了空的字符串“”
@Override
protected Integer doInBackground(String... params) {
resXML = ServiceInfo.Login(txtId.getText().toString(),txtPwd.getText().toString());
int i = AnalysisXML.AnalysisResult(resXML).getResultCount();
// publishProgress(i);//触发onProgressUpdate()方法,发布更新消息
}
//该方法在doInBackground()方法执行完成之后再运行,并且运行在UI线程当中
//onPostExecute(Integer result)里的参数为doInBackground()方法的返回值
//主要用于将异步任务执行的结果展示给客户。
protected void onPostExecute(Integer result) {
redirectMain(result);//这是一个页面跳转的方法,用于更新UI,此处不给出
}
//在doInBackground()方法中,每次调用publisProgress()方法之后,都会触发该方法,该方法执行在UI线程当中,因此可以更新UI
//主要用于在异步执行的过程当中对用户进行提示,如更新进度条等
// TODO Auto-generated method stub
System.out.println("onprogressUpdate=====>"+ Thread.currentThread().getName());
super.onProgressUpdate(values);
bar_seva.setProgress(values[0]);//更新进度条
}
}