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比同步适配器更可取。