如何在 android 应用程序中为 Web 服务调用创建通用 AsyncTask class?

How to create a common AsyncTask class for webservice call in an android app?

我正在尝试编写一个通用的网络服务 class,其中在我的应用程序中的任何活动都必须指向这个通用的 class 用于网络服务的东西。 目前我被困在两者之间;将 success/failure 消息传递给调用方 class, 我当前的实现如下所示, 我有一个接口 class,其中有 2 个方法,

 public void webServiceReqExecutedSuccessfully();
 public void webSerReqFailed();

并且每个 Web 服务调用 class 都根据其要求实施这些方法。 我常用的网络服务 class 如下所示,

    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;
           }
          }
         }
        }

我的问题是在服务调用响应之后,我如何 notify/invoke 从哪个对象引用调用 class 接口方法(webServiceReqExecutedSuccessfully() / webSerReqFailed())? 提前感谢任何帮助。谢谢

创建 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);
  }
}