1.AsyncTask被其他类A继承,Activity可以通过execute调用执行,execute的参数可以有多个,这个参数会作为类A从AsynTask继承的doInBackground方法的参数,同时它还是AsyncTask的第一个参数。
2.doInBackground方法的返回值会自动作为onPostExecute的参数,这个参数一般是服务器端对所发请求的返回结果。
下边例子分析:外部代码通过调用Httpnet 的execute,代码自动进入Httpnet ,先执行onPreExecute,再执行
doInBackground它的参数个数不定,但是它的参数是在外部调用Httpnet 的execute时execute的参数。
例如我在一个Activity里写Httpnet hp = new Httpnet (this)。hp.execute(url,“Get”)。下边的代码就适用,如果
是post下边的代码太适用。这时doInBackground的参数就是url和“Get”。
3.在doInBackground 执行完成后返回后台结果,onPostExecute 方法将被调用,后台的计算结果会作为onPostExecute 的参数。
举例代码:
public class Httpnet extends AsyncTask<String, Integer, HttpResponseParam> {
private final ProgressDialog dialog;
private static final int REGISTRATION_TIMEOUT = 3 * 1000;
private static final int WAIT_TIMEOUT = 5 * 1000;
private static final String TAG = "ExTraceHttpUtils";
private static final String USER_AGENT = "Mozilla/4.5";
public Httpnet(Activity context){
dialog = new ProgressDialog(context);
}
@Override
protected void onPreExecute() {
dialog.setMessage("正在更新数据...");
dialog.show();
}
@Override
protected HttpResponseParam doInBackground(String... params) {
String http_uri;
HttpResponseParam responseObj = new HttpResponseParam();
http_uri = params[0];
HttpClient client = new DefaultHttpClient();
final HttpParams http_params = client.getParams();
HttpConnectionParams.setConnectionTimeout(http_params,
REGISTRATION_TIMEOUT);
HttpConnectionParams.setSoTimeout(http_params, WAIT_TIMEOUT);
ConnManagerParams.setTimeout(http_params, WAIT_TIMEOUT);
publishProgress(30);
HttpResponse response;
HttpGet getMethod = new HttpGet(http_uri);
getMethod.setHeader("User-Agent", USER_AGENT);
getMethod.setHeader("Accept", "application/json");
try {
response = client.execute(getMethod);
HttpEntity entity;
entity = response.getEntity();
responseObj.responseString = EntityUtils.toString(entity,"utf8");
responseObj.statusCode = 1;
} catch (IOException e) {
responseObj.responseString = "服务器连接错误";
responseObj.statusCode = 0;
e.printStackTrace();
}
return responseObj;
}
@Override
protected void onPostExecute(HttpResponseParam result) {
if (result.statusCode == 0) {
dialog.setMessage(result.responseString);
dialog.show();
} else {
dialog.setMessage("连接成功:" + result.responseString);
dialog.show();
}
// dialog.dismiss();
}
}