我可以用volley完成同步請(qǐng)求嗎?假設(shè)我在一個(gè)已經(jīng)有后臺(tái)線程的服務(wù)中。我是否可以在同一個(gè)線程中使用volley執(zhí)行請(qǐng)求,以便回調(diào)同步進(jìn)行?這有兩個(gè)原因:-首先,我不需要另一個(gè)線程,創(chuàng)建它將是一種浪費(fèi)。-第二,如果我在ServiceIntent中,線程的執(zhí)行將在回調(diào)之前完成,因此,我將不會(huì)得到volley的響應(yīng)。我知道我可以創(chuàng)建我自己的服務(wù),它有一個(gè)我可以控制的運(yùn)行循環(huán)線程,但是在volley中使用這個(gè)功能是可取的。謝謝!
3 回答

RISEBY
TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超5個(gè)贊
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}

翻翻過(guò)去那場(chǎng)雪
TA貢獻(xiàn)2065條經(jīng)驗(yàn) 獲得超14個(gè)贊
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; }
添加回答
舉報(bào)
0/150
提交
取消