2014-06-30 60 views
3

我找不到更新的答案。我正在使用Volley向Web API發送請求。它返回JSON。我正在使用下面的緩存功能,但我想確保listview每隔一段時間刷新一次(比如現在說30分鐘)。我如何使這個給定的URL的緩存無效,讓我的應用程序自動處理(無刷新按鈕)。這question有助於指出無效和刪除之間的區別。Android Volley,無效緩存並每隔(x)分鐘發出一次新請求

MainActivity.java

Cache cache = AppController.getInstance().getRequestQueue().getCache(); 
     Entry entry = cache.get(URL_FEED); 
     if (entry != null) { 
      // fetch the data from cache 
      try { 
       String data = new String(entry.data, "UTF-8"); 
       try { 
        parseJsonFeed(new JSONArray(data)); 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 
      } catch (UnsupportedEncodingException e) { 
       e.printStackTrace(); 
      } 

     } else 
     { 
      // making fresh volley request and getting json 

      JsonArrayRequest getRequest = new JsonArrayRequest(URL_FEED, 
        new Response.Listener<JSONArray>() 
        { 
         @Override public void onResponse(JSONArray response) { 
          VolleyLog.d(TAG, "Response: " + response.toString()); 
          if (response != null) { 
           parseJsonFeed(response); 
          } 
          Log.d("Response", response.toString()); 
         } 
        },......ErrorListener 

回答

4

要刷新列表視圖,您可以用凌空的serverDate來獲得日期時的響應最初收到

AppController.getInstance().getRequestQueue().getCache().get(url).serverDate 

該返回日期時間長了。 並在代碼中使用minutedifference功能

public static long getMinutesDifference(long timeStart,long timeStop){ 
      long diff = timeStop - timeStart; 
      long diffMinutes = diff/(60 * 1000); 

      return diffMinutes; 
     } 

,並在代碼中調用該函數作爲

Calendar calendar = Calendar.getInstance(); 
long serverDate = AppController.getInstance().getRequestQueue().getCache().get(url).serverDate; 
if(getMinutesDifference(serverDate, calendar.getTimeInMillis()) >=30){ 
    AppController.getInstance().getRequestQueue().getCache().invalidate(URL_FEED, true); 
} 

它將緩存失效,如果以前的URL響應> = 30分鐘。

這個(invalidate)允許繼續使用這些數據,直到進行新的調用並且緩存的響應被新的響應覆蓋。

+0

它工作不正常。 – JosephM

+0

@ HemsLodha你的意思是不正確嗎?請詳細說明。 –

+0

現在我的作品出現了問題,謝謝@Giru Bhai。但是當我們通過抽頭向服務器請求數據時,緩存應該在一段時間內過期。可能嗎 ?如果是,那麼如何? – JosephM

相關問題