我可以用volley完成同步請求嗎?假設我在一個已經有后臺線程的服務中。我是否可以在同一個線程中使用volley執行請求,以便回調同步進行?這有兩個原因:-首先,我不需要另一個線程,創建它將是一種浪費。-第二,如果我在ServiceIntent中,線程的執行將在回調之前完成,因此,我將不會得到volley的響應。我知道我可以創建我自己的服務,它有一個我可以控制的運行循環線程,但是在volley中使用這個功能是可取的。謝謝!
3 回答
RISEBY
TA貢獻1856條經驗 獲得超5個贊
RequestFuture
RequestFuture<JSONObject> future = RequestFuture.newFuture();JsonObjectRequest request = new JsonObjectRequest(URL, new JSONObject(),
future, future);requestQueue.add(request);try {
JSONObject response = future.get(); // this will block} catch (InterruptedException e) {
// exception handling} catch (ExecutionException e) {
// exception handling}
翻翻過去那場雪
TA貢獻2065條經驗 獲得超14個贊
get()future.get(30, TimeUnit.SECONDS)
try {
return future.get(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// exception handling
} catch (ExecutionException e) {
// exception handling
} catch (TimeoutException e) {
// exception handling
} /**
* Runs a blocking Volley request
*
* @param method get/put/post etc
* @param url endpoint
* @param errorListener handles errors
* @return the input stream result or exception: NOTE returns null once the onErrorResponse listener has been called
*/
public InputStream runInputStreamRequest(int method, String url, Response.ErrorListener errorListener) {
RequestFuture<InputStream> future = RequestFuture.newFuture();
InputStreamRequest request = new InputStreamRequest(method, url, future, errorListener);
getQueue().add(request);
try {
return future.get(REQUEST_TIMEOUT, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Log.e("Retrieve cards api call interrupted.", e);
errorListener.onErrorResponse(new VolleyError(e));
} catch (ExecutionException e) {
Log.e("Retrieve cards api call failed.", e);
errorListener.onErrorResponse(new VolleyError(e));
} catch (TimeoutException e) {
Log.e("Retrieve cards api call timed out.", e);
errorListener.onErrorResponse(new VolleyError(e));
}
return null;
}添加回答
舉報
0/150
提交
取消
