如何管理需要由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
}
传递线程的处理程序:
您需要将处理程序传递给参数中的上述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
- 难以将用户1的位置发送给用户2,将用户2的位置发送给用户1?
- 如何在android中逐字搜索
- Android:具有进度对话框的重型DB操作
- 如何从HttpClient切换到HttpUrlConnection?
- 使用Retrofit反序列化带有文本和子标签的XML标记
- 从WiFi连接切换到3g导致连接挂起?
- 试图运行琐碎的Android JUnit测试。 获得:“测试运行失败:没有测试结果”我缺少什么?
- 检索项目的父项时出错:找不到与给定名称“Theme.AppCompat.Light”匹配的资源。 我的R.java失踪了
- BitmapFactory无法解码流:Android中的java.io.FileNotFoundException