我正在尝试编写一个常见的Web服务类,其中我的应用程序中的任何活动都必须指向Web服务的这个公共类。 目前我陷入了困境之中;将成功/失败消息传递给调用类, 我目前的实施如下, 我有一个接口类,我有2个方法,
public void webServiceReqExecutedSuccessfully();
public void webSerReqFailed();
并且每个webservice调用类都根据其要求实现这些方法。 我的常见Web服务类如下所示,
public class WebServiceRequest extends AsyncTask < String, Void, Boolean>
{
private static final MediaType FORM_DATA_TYPE = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
public enum HTTPServiceTags {
POST_IT,
GET_ALL_ITEMS
}
HTTPServiceTags requestTag;
public ATWebServiceRequest(HTTPServiceTags reqTag, Callable < Void > _ServiceResponseSuccess, Callable < Void > _ServiceResponseFailure) {
this.requestTag = reqTag;
}
@Override
protected Boolean doInBackground(String...postDataSet) {
Boolean result = true;
String requestURL = postDataSet[0];
String postBody = getPostBody(postDataSet);
Log.d(requestURL, postBody);
try {
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(FORM_DATA_TYPE, postBody);
Request request = new Request.Builder().url(requestURL).post(body).build();
Response response = client.newCall(request).execute();
} catch (IOException exception) {
result = false;
}
return result;
}
@Override
protected void onPostExecute(Boolean result) {
if (result) {
switch (requestTag) {
case POST_IT:
//HOW CAN I NOTIFY/INVOKE webServiceReqExecutedSuccessfully METHOD OF THE CALLING CLASS HERE???
break;
case GET_ALL_ITEMS:
break;
default:
break;
}
}
}
}
我的问题是在服务调用响应后如何通知/调用调用类接口方法(webServiceReqExecutedSuccessfully()/ webSerReqFailed())从哪个对象引用? 任何帮助都提前感谢。感谢
答案 0 :(得分:0)
创建将用作回调的Interface
。
public interface MyCallBack {
void onResult(HTTPServiceTags requestTag);
}
在Activity
实现该界面 -
public class Xyz extends Activity implements MyCallBack {
@override
public void void onResult(HTTPServiceTags requestTag) {
// Do your work
}
}
在AsyncTask的构造函数中传递该接口 -
public WebServiceRequest(MyCallBack callBack) {
this.mCallBack = callBack; // Assign it to global variable
}
然后在onPostExecute
中调用它 -
@Override
protected void onPostExecute(Boolean result) {
if (result) {
mCallBack.onResult(requestTag);
}
}