创建MAsyncTask类
/**
* @ClassName: MyAsyncTask
* @Description: 用于执行一些耗时的异步操作, 用户通过Handler接收执行该异步操作返回的数据。
* @author: Tony.Zhang
* @date:2012-4-13 下午3:12:00
*/
public class MAsyncTask extends AsyncTask<CommCmdBean, Void, CommRetBean> {
private static final String TAG = MAsyncTask.class.getSimpleName();
private boolean isWantStop = false; // 是否想要停止加载数据
/** 成功 加载数据 */
public static final int OK_MESSAGE = 0;
/** 失败 加载数据 ConnectException */
public static final int ERROR_MESSAGE_CONNECTEXCEPTION = 1;
/** 失败 加载数据 NetworkErrorException */
public static final int ERROR_MESSAGE_NETWORKERROR = 2;
/** 失败 加载数据 JsonParseException */
public static final int ERROR_MESSAGE_JSONPARSE = 3;
/** 失败 加载数据 TimeoutException */
public static final int ERROR_MESSAGE_TIMEOUT = 4;
/** 失败 加载数据 SocketTimeoutException */
public static final int ERROR_MESSAGE_SOCKETTIMEOUT = 5;
/** 失败 加载数据 IOException --> RequestFail */
public static final int ERROR_MESSAGE_IOEXCEPTION = 6;
/** 失败 加载数据 未知其他错误 */
public static final int ERROR_MESSAGE_OTHERS = 7;
private IMAsyncService mAsyncService;
private Context mContext = null;
private Handler mHandler = null;
private ProgressDialog mPDialog = null;
private CommCmdBean mCommCmdBean = null;
private CommRetBean mCommRetBean = null;
private String mServerURL = null;
/** KEY 用于bundle所传递的对象key值, 该 传递对象需实现Serializable */
public final static String KEY_HANDLER_DATA = "key_handler_data";
public MAsyncTask(Context context, Handler handler,
IMAsyncService myAsyncService, String serverURL) {
this.mContext = context;
this.mHandler = handler;
this.mAsyncService = myAsyncService;
this.mServerURL = serverURL;
}
@Override
protected void onPreExecute() {
isWantStop = false; // 每次开始加载时,
if (SystemTool.getNetWorkState(mContext)) {
showProgressDialog();// 每次开始执行异步任务时 显示登录对话框
} else {
// Toast.makeText(mContext,
// mContext.getString(R.string.netWorkError0), Toast.).show();
// 打开网络设置
Dialog.netWorkErrDialog(mContext, R.string.netWorkError0);
this.cancel(true);// 取消任务
isWantStop = true;
}
super.onPreExecute();
}
@Override
protected CommRetBean doInBackground(CommCmdBean... params) {
mCommCmdBean = params[0];
// 执行耗时操作
try {
mCommRetBean = mAsyncService.executeAsyncPostRequest(mCommCmdBean, mServerURL);
} catch (ConnectException e) {
e.printStackTrace();
Log.e(TAG, " ---------> ConnectException ");
sendErrorMessage(ERROR_MESSAGE_CONNECTEXCEPTION);
return null;
} catch (NetworkErrorException e) {
e.printStackTrace();
Log.e(TAG, " ---------> NetworkErrorException ");
sendErrorMessage(ERROR_MESSAGE_NETWORKERROR);
return null;
} catch (JsonParseException e) {
e.printStackTrace();
Log.e(TAG, " ---------> JsonParseException ");
sendErrorMessage(ERROR_MESSAGE_JSONPARSE);
return null;
} catch (TimeoutException e) {
e.printStackTrace();
Log.e(TAG, " ---------> TimeoutException ");
sendErrorMessage(ERROR_MESSAGE_TIMEOUT);
return null;
} catch (SocketTimeoutException e) {
e.printStackTrace();
Log.e(TAG, " ---------> SocketTimeoutException ");
sendErrorMessage(ERROR_MESSAGE_SOCKETTIMEOUT);
return null;
} catch (RequestFail e) {
e.printStackTrace();
Log.e(TAG, " ---------> RequestFail ");
sendErrorMessage(ERROR_MESSAGE_IOEXCEPTION);
return null;
} catch (Exception e) {// ???????
e.printStackTrace();
Log.e(TAG, " ---------> Exception ");
sendErrorMessage(ERROR_MESSAGE_OTHERS);
return null;
}
return mCommRetBean;
}
@Override
protected void onPostExecute(CommRetBean result) {
hideProgressDialog();// 异步请求完成, 隐藏加载对话框
if (result != null) {
// 发送消息
sendSuccessMessage(OK_MESSAGE, result);
} else {
sendErrorMessage(ERROR_MESSAGE_OTHERS);
}
}
/**
* Description: 显示加载对话框
*
*/
private void showProgressDialog() {
if (mPDialog == null) {
mPDialog = new ProgressDialog(mContext);
mPDialog.setTitle(mContext.getString(R.string.loading_data));
mPDialog.setMessage(mContext.getString(R.string.waiting));
mPDialog.setIndeterminate(true);
mPDialog.setCancelable(false);
mPDialog.setCancelable(true);
mPDialog.setButton(mContext.getString(R.string.cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (mPDialog != null) {
mPDialog.dismiss();
}
isWantStop = true; // 用户想要停止加载
}
});
mPDialog.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
// 用户可能并每有点击取消按钮, 而是点击了返回键
isWantStop = true; // 用户想要停止加载
}
});
}
mPDialog.show();
}
/**
* Description: 适用异步任务开始请求服务器端数据,通过Handler可接收返回数据
*
* @param context
* @param handler
* @param mAsyncService
* @param serverUrl
* 请求的服务器URL
* @param commCmdBean
* 请求服务需要Post的对象, 目前务必要给commCmdBean.requestService赋值(表示请求的接口方法名)
*/
public static void startRequestServerData(Context context, Handler handler,
IMAsyncService mAsyncService, String serverUrl,
CommCmdBean commCmdBean) {
new MAsyncTask(context, handler, mAsyncService, serverUrl) .execute(commCmdBean);
}
/**
* Description: 隐藏加载对话框
*
*/
private void hideProgressDialog() {
if (mPDialog != null) {
mPDialog.dismiss();
mPDialog = null;
}
}
/**
* Description: 通过Handler回调通知用户是否成功的加载了数据
*
* @param messageWhat
*/
private void sendErrorMessage(int messageWhat) {
Log.i(TAG, "ErrorMessage --> isWantStop ? " + isWantStop);
if (!isWantStop) {
Message message = new Message();
message.what = messageWhat;
if (mHandler != null) {
mHandler.sendMessage(message);
}
}
}
/**
* Description: 通过Handler回调通知用户是否成功的加载了数据
*
* @param messageWhat
*/
private void sendSuccessMessage(int messageWhat, Object object) {
Log.i(TAG, "SuccessMessage --> isWantStop ? " + isWantStop);
if (!isWantStop) {
Message message = new Message();
message.what = messageWhat;
Bundle bundle = new Bundle();
bundle.putSerializable(KEY_HANDLER_DATA, (CommRetBean) object);
message.setData(bundle);
if (mHandler != null) {
mHandler.sendMessage(message);
}
}
}
}
MAsyncService类
/**
* @ClassName: MAsyncService
* @Description: 用于执行异步耗时操作
* @author: Tony.Zhang
* @date:2012-5-9 上午10:46:00
*/
public class MAsyncService implements IMAsyncService {
private static final String tag = MAsyncService.class.getSimpleName();
private Context applicationContext;
public MAsyncService(Context context) {
this.applicationContext = context;
}
@Override
public CommRetBean executeAsyncPostRequest(Object obj, String url)
throws ConnectException, NetworkErrorException, TimeoutException,
JsonParseException, SocketTimeoutException, RequestFail {
String httpResponseString = null;
CommRetBean commRetBean = null;
String postJsonString = null;
if (obj != null) {
postJsonString = SystemTool.gson.toJson(obj);
} else {
return null;
}
Log.d(tag, "postJsonString == " + postJsonString);
httpResponseString = HttpCaller.getInstance().doPostRequest(
applicationContext, postJsonString, url, 60 * 1000);
if (httpResponseString != null && !"".equals(httpResponseString)) {
commRetBean = SystemTool.gson.fromJson(httpResponseString,
CommRetBean.class);
}
return commRetBean;
}
@Override
public CommRetBean executeAsyncGetRequest(String serverURL)
throws TimeoutException, NetworkErrorException, ConnectException,
JsonParseException, SocketTimeoutException, RequestFail {
// TODO Auto-generated method stub
return null;
}
}
HttpCaller工具类
/**
* @ClassName: HttpCaller
* @Description: 一个工具类 , 用于执行HTTP请求, 请求是一个耗时的操作,需在线程或其它异步操作中执行。
* @author: Tony.Zhang
* @date:2012-4-13 下午4:36:40
*/
public class HttpCaller {
private static final String TAG = HttpCaller.class.getSimpleName();
private static HttpCaller instance;
private static final String CONTENT_TYPE = "Content-Type";
private static final String CONTENT_TYPE_VALUE = "application/json";
private HttpClient mHttpClient = null;
private HttpParams myParams = null;
private HttpPost mHttpPost = null;
private HttpGet mHttpGet = null;
private HttpCaller(){};
public static HttpCaller getInstance(){
if(instance == null){
instance = new HttpCaller();
}
return instance;
}
/**
* Description: 执行HTTP post请求
* @param context
* @param postJson
* @param serverUrl
* @param timeOut 请求超时时间 单位毫秒
* @return String
* @throws ClientProtocolException
* @throws TimeoutException
* @throws NetworkErrorException
* @throws ConnectException
* @throws IOException
*/
public String doPostRequest(Context context, String postJson, String serverUrl ,int timeOut) throws RequestFail {
HttpResponse response = null;
String responseString = null;
StringEntity tmp = null;
this.getHttpClient(timeOut);
this.getHttpPost(serverUrl);
Log.i(TAG ,"Request serverUrl is: " + serverUrl );
try {
tmp = new StringEntity(postJson, Constant.CHARACTER_GBK); //HTTP.UTF_8
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
return null;
}
this.mHttpPost.setEntity(tmp);
try {
response = this.mHttpClient.execute(this.mHttpPost);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(TAG, "Error " + statusCode + " while retrieving data from " + serverUrl);
return null;
}
if (response != null ) {
responseString = EntityUtils.toString(response.getEntity());
Log.d(TAG, "Response: " + responseString);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
abortHttpPost();
throw new RequestFail(); //抛出自定义异常
} catch (ParseException e) {
e.printStackTrace();
abortHttpPost();
throw new RequestFail(); //抛出自定义异常
} catch (IOException e) {
e.printStackTrace();
abortHttpPost();
throw new RequestFail(); //抛出自定义异常
} finally{// TODO: handle exception 关闭连接
if (this.mHttpClient != null && this.mHttpClient.getConnectionManager() != null) {
this.mHttpClient.getConnectionManager().shutdown();
}
}
return responseString;
}
/**
* Description: 执行HTTP post请求
* @param context
* @param serverUrl
* @param timeOut 请求超时时间 单位毫秒
* @return String
* @throws ClientProtocolException
* @throws TimeoutException
* @throws NetworkErrorException
* @throws ConnectException
* @throws IOException
*/
public String doGetRequest(Context context, String serverUrl ,int timeOut) throws RequestFail {
HttpResponse response = null;
String responseString = null;
this.getHttpClient(timeOut);
this.getHttpGet(serverUrl);
Log.i(TAG ,"Request serverUrl is: " + serverUrl );
try {
response = this.mHttpClient.execute(this.mHttpGet);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(TAG, "Error " + statusCode + " while retrieving data from " + serverUrl);
return null;
}
if (response != null ) {
responseString = EntityUtils.toString(response.getEntity());
Log.d(TAG, "Response: " + responseString);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
abortHttpPost();
throw new RequestFail(); //抛出自定义异常
} catch (ParseException e) {
e.printStackTrace();
abortHttpPost();
throw new RequestFail(); //抛出自定义异常
} catch (IOException e) {
e.printStackTrace();
abortHttpPost();
throw new RequestFail(); //抛出自定义异常
} finally{// TODO: handle exception 关闭连接
if (this.mHttpClient != null && this.mHttpClient.getConnectionManager() != null) {
this.mHttpClient.getConnectionManager().shutdown();
}
}
return responseString;
}
/**
* Get the HttpClient, Set Timeout
* @return HttpClient
*/
public HttpClient getHttpClient(int timeOut){
myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, timeOut);
HttpConnectionParams.setSoTimeout(myParams, timeOut);
mHttpClient = new DefaultHttpClient(myParams);
return this.mHttpClient;
}
public HttpPost getHttpPost(String url){
if(url != null){
url = url.replaceAll(" ", "%20");
}
this.mHttpPost = new HttpPost(url);
this.mHttpPost.setHeader(CONTENT_TYPE, CONTENT_TYPE_VALUE);
return this.mHttpPost;
}
public HttpGet getHttpGet(String url){
if(url != null){
url = url.replaceAll(" ", "%20");
}
this.mHttpGet = new HttpGet(url);
return this.mHttpGet;
}
private void abortHttpPost(){
if (mHttpPost != null) {
mHttpPost.abort();
}
}
}
使用时, 需要在Activity中定义Handler 用户处理消息
MAsyncTask.startRequestServerData(CustomerSelectedActivity.this, handler, mAsyncService, Constant.URL_SERVER, commCmdBean);