1

我開發了一個使用sqlite數據庫的應用程序。該應用程序需要comunicate /下列事件後同步(主 - 主)的一些數據庫表:Volley libary vs Android SyncAdapter

  • 在應用程序啓動
  • 在點擊刷新按鈕
  • 在情況下,如果使用執行某些操作而改變數據在sqlite數據庫

如果應用程序未運行,android sqlite數據庫不需要同步。每個同步請求需要擴展Authorization headerVolley庫已經集成在應用程序中。

問題是(考慮上面的用例)應該更好地使用Volley庫的應用程序和服務器之間的通信或實現AsyncAdapter?有可能結合這兩種方法?

謝謝

+0

使用SyncAdapter附帶了像AccountManager,Loaders和Content Providers等附加軟件包。它們協同工作,以較少的資源保持數據的最新狀態。 – Skynet

回答

0

Syncadapter是處理服務器和客戶端SyncAdapter

之間定期同步的看着你的應用程序需要,我會建議抽射。

4

SyncAdapter應該使用凌空數據獲取這樣的:

public class SyncAdapter extends AbstractThreadedSyncAdapter { 

    @Override 
    public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, final SyncResult syncResult) { 
    RequestQueue queue = VolleyService.getInstance(this.getContext()).getRequestQueue(); 
     StringRequest request = new StringRequest(url, new Response.Listener<String>() { 

      @Override 
      public void onResponse(String response) { 
       // we got the response, now our job is to handle it 
       try { 
        //Parse JSON response and Insert/Update data to SQLite DB 
       } catch (RemoteException | OperationApplicationException e) { 
        e.printStackTrace(); 
       } 
      } 
     }, new Response.ErrorListener() { 

      @Override 
      public void onErrorResponse(VolleyError error) { 
       //something happened, treat the error. 
      } 
     }); 

     queue.add(request); 

    } 

} 

SyncAdapter用於同步按需或定期的數據。在您的內容解析,您可以設置刷新和週期的類型:

ContentResolver.addPeriodicSync(account, "com.android.app", params, 150); 
ContentResolver.setSyncAutomatically(account, "com.android.app", true); 

凌空服務:

public class VolleyService { 

    private static VolleyService instance; 
    private RequestQueue requestQueue; 
    private ImageLoader imageLoader; 

    private VolleyService(Context context) { 
     requestQueue = Volley.newRequestQueue(context); 

     imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() { 
      private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20); 

      @Override 
      public Bitmap getBitmap(String url) { 
       return cache.get(url); 
      } 

      @Override 
      public void putBitmap(String url, Bitmap bitmap) { 
       cache.put(url,bitmap); 
      } 
     }); 
    } 

    public static VolleyService getInstance(Context context) { 
     if (instance == null) { 
      instance = new VolleyService(context); 
     } 
     return instance; 
    } 

    public RequestQueue getRequestQueue() { 
     return requestQueue; 
    } 

    public ImageLoader getImageLoader() { 
     return imageLoader; 
    } 
} 
+1

onPerformSync方法在異步數據處理完成之前結束(複雜的排隊請求可能需要幾秒鐘的時間...可能是一個問題嗎?例如可能是由系統退出的SynchAdapter線程爲「不再使用」? – Wooff

1

同步適配器異步運行,所以你應該將它們與預期使用,他們經常和有效的傳輸數據,但不是即時。如果你需要做實時數據傳輸,你應該使用Volley(或者基本上是一個AsyncTask或一個IntentService)。 Refer Android documentation.因此,在你的情況下,Volley比同步適配器更可取。