2017-10-05 95 views
0

我有以下代碼,它可以用來進行呼叫並接收xml。排隊使用StringRequest和RequestFuture進行阻塞同步呼叫

StringRequest stringRequest = new StringRequest(Request.Method.GET, url, 
        new Response.Listener<String>() { 
         @Override 
         public void onResponse(String response) { 
          // Do something with the response 
          Log.e(TAG, "response from RRSendCarerLocation = " + response); 

         } 
        }, 
        new Response.ErrorListener() { 
         @Override 
         public void onErrorResponse(VolleyError error) { 
          // Handle error 
          Log.e(TAG, "error: RRSendCarerLocation = " + error); 



         } 
        }); 


      rq.add(stringRequest); 

我遇到的問題是,當從一個活動調用時,這工作正常,但我想從一個IntentService使用Volley。工作完成後intentService會自行破壞,所以Volley回調永遠不會檢索響應。

我發現的一個解決方案是使用RequestFuture並調用.get()來阻塞線程。我在這裏找到了一個例子。

Can I do a synchronous request with volley?

RequestFuture<JSONObject> future = RequestFuture.newFuture(); 
JsonObjectRequest request = new JsonObjectRequest(URL, new JSONObject(), future, future); 
requestQueue.add(request); 

try { 
      return future.get(30, TimeUnit.SECONDS); 
     } catch (InterruptedException e) { 
      // exception handling 
     } catch (ExecutionException e) { 
      // exception handling 
     } catch (TimeoutException e) { 
      // exception handling 
     } 

我不想使用JSON作爲服務器返回xml。我已經看過了StringRequest類,但是我看不到任何支持RequestFuture的東西。

http://griosf.github.io/android-volley/com/android/volley/toolbox/StringRequest.html

反正是有使用StringRequest代碼中使用RequestFuture

感謝

回答

0

我用改造爲這個類型的請求的攔截功能中返回XML。這是非常容易使用,並允許你做出這兩種類型的請求(同步和異步) http://square.github.io/retrofit/

+0

嗨,所以我想不能在Volley做?看起來奇怪的是,Android已經採用了Volley,並且不能從IntentService中使用。我會看看Retrofit,但我想用盡Volley的所有可能性 – turtleboy