1
在我的Android應用程序中,我從一個Activity進行多個API調用。我正在使用以下方法:在Activity中實現接口並從Async類調用該接口函數。使用回調接口實現AsyncTask - 在單個回調接口中處理多個呼叫響應
public interface AsyncResponse {
public void processFinish(JSONObject sb);
}
public class FetchData extends AsyncTask<String, Integer, JSONObject> {
HttpURLConnection urlConnection;
String url;
String method;
String payload = null;
AsyncResponse delegate = null;
public FetchData(AsyncResponse delegate, String url, String method) {
this.delegate = delegate;
this.url = url;
this.method = method;
}
public FetchData(AsyncResponse delegate, String url, String method, JSONObject payload) {
this(delegate, url, method);
this.payload = payload.toString();
}
@Override
protected JSONObject doInBackground(String... args) {
BufferedReader reader = null;
try {
URL url = new URL(this.url);
// Open HTTP connection
urlConnection = (HttpURLConnection) url.openConnection();
// HTTP method GET/POST/PUT/DELETE
urlConnection.setRequestMethod(this.method);
// handle issues
int statusCode = urlConnection.getResponseCode();
// Get the response
InputStream inputStream = urlConnection.getInputStream();
if(inputStream == null) {
// Nothing to do
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String inputLine = null;
StringBuffer response = new StringBuffer();
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine + "\n");
}
return new JSONObject(response.toString());
} catch(Exception e) {
try {
// Return error response
} catch(Exception e1) {
System.out.println(e1);
return null;
}
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
}
@Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
this.delegate.processFinish(result);
}
}
public class AsyncTasks extends AppCompatActivity implements AsyncResponse {
TextView view = null;
int a = 1;
Utility utility = Utility.getInstance();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_async_tasks);
new FetchData(this, "<url 1>", "GET").executeOnExecutor(THREAD_POOL_EXECUTOR);
new FetchData(this, "<url 2>", "GET").executeOnExecutor(THREAD_POOL_EXECUTOR);
}
@Override
public void processFinish(JSONObject data) {
utility.showDialog(this, data.toString());
}
}
這裏如何處理processFinish()接口函數第二GET調用的響應?什麼是最好的方法?
如果兩個網址都不同,那麼只需添加條件以匹配所提供的url並讀取響應。 –
可能有相同的URL的機會。有什麼辦法通過設置標籤或其他方式來識別呼叫嗎?請提供示例代碼。 – Sivakumar
我會爲您的FetchData的構造函數添加一些請求ID,並將其傳回processFinish以區分這兩個請求。 – Viacheslav