在我的 Android 应用程序中,我发现我所有的 api 调用都在排队,而不是同时发生。我假设它们都被发布到同一个线程,而我的印象是 anAsyncTask
创建了一个新线程doInBackground()
。
public class API extends AsyncTask<String, String, String> {
public interface Listener {
void completedWithResult(JSONObject result);
}
public Listener listener;
@Override
protected String doInBackground(String... strings) {
if(!canMakeRequest()){
return internetError().toString();
}
String action = strings[0];
Log.i("API", action +" Sent");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i("API", action +" Received");
return "";
}
@Override
protected void onPostExecute(String json) {
JSONObject obj;
obj = new JSONObject(json);
if(listener != null)listener.completedWithResult(obj);
}
}
在我的应用程序的一大堆地方,我有类似的东西:
API api = new API();
api.listener = new API.Listener() {
@Override
public void completedWithResult(JSONObject result) {
Log.i(tag, "Returned with "+result);
}
};
api.execute("update-address/");
而且我总是创建一个新的实例API
,但是我的日志中所有这些调用都是连续发生的,而不是并行发生的:
analytics/log/ Sent
analytics/log/ Returned
get-beta-tester Sent
get-beta-tester Returned
get-following Sent
get-following Returned
get-groups Sent
get-groups Returned
get-follow-requests Sent
get-follow-requests Returned
get-followers Sent
get-followers Returned
analytics/log/ Sent
analytics/log/ Returned
analytics/log/ Sent
analytics/log/ Returned
post-session Sent
post-session Returned
analytics/log/ Sent
analytics/log/ Returned
post-session Sent
post-session Returned
analytics/log/ Sent
analytics/log/ Returned
analytics/log/ Sent
analytics/log/ Returned
unregister-GCM Sent
unregister-GCM Returned
analytics/log/ Sent
analytics/log/ Returned
verify Sent
verify Returned