我有一个外部库可以使用,它通过互联网与服务器进行通信。每当我需要从互联网获取一些信息时,Android 都会强制我使用异步任务。到目前为止没有问题。但是,我收到越来越多的任务来从互联网检索(以不同方式)数据,并且我不喜欢为每个调用增加不同的类。
长话短说:我有不同的互联网调用,而不是为每个调用创建一个异步任务类,我更喜欢一个类来管理所有不同的调用。这有可能吗?更重要的是,正确的方法是什么?
我也面临着像你一样的类似问题。但我通过反射技术解决了这个问题。我制定了一种方法来防止增加不同类来调用单次命中。
我创建了单个 asynctask 类并传递了 functionName 和活动上下文,并通过 onPostExecute 返回了响应。
这是样本 -
AsyncTaskConnection.java
public class AsyncTaskConnection extends AsyncTask<String, String, Object>{
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();
}
}
有很多方法可以获得您想要的结果。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)