如何管理需要由AsyncTask调用的不同任务

我有一个外部库,可以通过互联网与服务器通信。 每当我需要从互联网上获取一些信息时,android会强迫我使用asynctask。 到目前为止没问题。 但是,我正在接收越来越多的任务来从互联网上检索(以不同的方式)数据,而且我不喜欢每次调用不同类的增加。 长话短说:我有不同的互联网调用,而不是为每个调用创建一个asynctask类,我会优先选择一个类来管理所有不同的调用。 这有点可能吗? 更重要的是,这样做的正确方法是什么?

我也像你一样面对similer问题。但我通过Reflection Technique解决了这个问题。 我已经制定了一种方法来防止增加不同的类来调用单击。 我创建了单个asynctask类,并传递了activity的活动名称和上下文,并通过onPostExecute返回了响应。

这是样本 –

AsyncTaskConnection.java

public class AsyncTaskConnection extends AsyncTask{ JSONObject mainObject; Context mContext; String returnFunctionName; public AsyncTaskConnection (Context context){ mContext = context; } protected void onPreExecute() { // preExecute } @Override protected Object doInBackground(String... arguments) { String apiFunctionName = arguments[0]; // get api FunctionName String jsonString = arguments[1]; // get data returnFunctionName = apiFunctionName+"Response"; // return function name // some connection code... //then call... try { ht.call(NAMESPACE, requestEnvelop); } catch (IOException ex) { Log.d(mContext.getClass().getName(), "Io exception bufferedIOStream closed" + ex); ex.printStackTrace(); } return mainObject.toString(); } catch (Exception e) { Log.d("Exception", e.toString()); return "no"; } } // main thing is there, i have use the reflaction here.... @Override protected void onPostExecute(Object backresult) { Method m; try { m = mContext.getClass().getDeclaredMethod(returnFunctionName, String.class); m.invoke(mContext, (String) backresult); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } 

在来电课程

 //call this class where you want and get dynamic response new AsyncTaskConnection(this).execute("getHomepage",jo.toString()); // and make response fuction protected void getHomepageResponse(String backresult) { try { // this is your response mainObject = new JSONObject(backresult); } catch (JSONException e) { e.printStackTrace(); } } 

并且可以通过多种方式获得您想要的结果。

是的,这是可能的,但你需要创建一些通用的AsyncTask,它接收API(url to call)和处理器收到结果。

异步类:

 public class AsyncTaskThread extends AsyncTask { //instance variables Handler myHandler; public AsyncTaskThread(String uriString, Handler myHandler) { //set these arguments to respective instance variables this.myHandler=myHandler; } protected Object doInBackground(Object... obj){ //business logic } //----implement other methods of Async as per your requirement @Override protected void onPostExecute(Object result) { super.onPostExecute(result); Message message = new Message(); message.obj = result; myHandler.sendMessage(message); } 

}

传递线程的处理程序:
您需要将处理程序传递给参数中的上述Async任务。

 new AsyncTaskThread(uri,new MyHandler()) import android.os.Handler; private class MyHandler extends Handler{ @Override public void handleMessage(Message msg) { Model response = (Model) msg.obj; } } 

当结果收到来自异步任务的传递处理程序调用sendMessage()方法时。

我的建议:
如果您使用okhttp客户端库进行API调用,请参阅https://github.com/square/okhttp/wiki/Recipes