亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

可以用volley完成同步請求嗎?

可以用volley完成同步請求嗎?

海綿寶寶撒 2019-08-02 03:03:47
我可以用volley完成同步請求嗎?假設我在一個已經有后臺線程的服務中。我是否可以在同一個線程中使用volley執行請求,以便回調同步進行?這有兩個原因:-首先,我不需要另一個線程,創建它將是一種浪費。-第二,如果我在ServiceIntent中,線程的執行將在回調之前完成,因此,我將不會得到volley的響應。我知道我可以創建我自己的服務,它有一個我可以控制的運行循環線程,但是在volley中使用這個功能是可取的。謝謝!
查看完整描述

3 回答

?
RISEBY

TA貢獻1856條經驗 獲得超5個贊

看上去這是有可能的RequestFuture班級,等級。例如,要創建同步的JSONHTTPGET請求,可以執行以下操作:

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}



查看完整回答
反對 回復 2019-08-04
?
翻翻過去那場雪

TA貢獻2065條經驗 獲得超14個贊

如果你在另一個線程上,當你沒有互聯網的時候,你會打一個截擊電話,您的錯誤回調將在主線程上調用,但您所在的線程將永遠被阻塞。(因此,如果該線程是IntentService,您將永遠無法向它發送另一條消息,并且您的服務將基本上死掉)。

使用get()有一個超時future.get(30, TimeUnit.SECONDS)并捕捉錯誤以退出線程。

匹配@mathews回答:

        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;
    }




查看完整回答
反對 回復 2019-08-04
  • 3 回答
  • 0 關注
  • 528 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號