public class Request extends AsyncTask {
private RequestListener emmaRequestListener = null;
private Object data = null;
private Exception _errorException = null;
//在后台异步启动TASK,AsyncTask提供了异步功能,需要重载其中的回调函数
@Override
protected Object doInBackground(RequestParameter... parameter) {
try {
RequestParameter emmaRequestParameter = parameter[0];
emmaRequestListener = emmaRequestParameter.requestListener;
data = emmaRequestParameter.data;
BaseTask task = emmaRequestParameter.task;
return task.execute();
}
catch (InvocationTargetException e) {
Throwable baseException = e.getCause() ;
if (baseException == null)
_errorException = new LocalGeneralException(e.getMessage());
else {
if (baseException instanceof ServerGeneralException)
{
_errorException = new ServerGeneralException(baseException.getMessage());
}
else if (baseException instanceof ServerAuthException)
{
_errorException = new ServerAuthException(baseException.getMessage());
}
else {
_errorException = new LocalGeneralException(baseException.getMessage());
}
}
}
catch (Exception e) {
_errorException = new LocalGeneralException(e.getMessage());
}
return _errorException;
}
//执行结束后,如果没有异常,则调用回调函数
@Override
protected void onPostExecute(Object result) {
if (_errorException == null) {
emmaRequestListener.onRequestSuccess(result, data);
} else {
emmaRequestListener.onRequestFailed(_errorException, data);
}
}
//中途如果被cancel掉
@Override
protected void onCancelled() {
emmaRequestListener.onRequestCanceled(data);
}
public interface RequestListener {
void onRequestSuccess(Object result, Object data);
void onRequestFailed(Object result, Object data);
// void onRequestCanceled(Object data);
}
//定义执行过程,需要加入task,如果成功会调用RequestListener所定义的函数
public static Request executeAsynRequest(BaseTask task,
RequestListener requestListener, Object data) {
RequestParameter requestParameter = new RequestParameter(task,
requestListener, data);
Request r = new Request();
r.execute(requestParameter);
return r;
}
}