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;
}
}
使用SyncAdapter附带了像AccountManager,Loaders和Content Providers等附加软件包。它们协同工作,以较少的资源保持数据的最新状态。 – Skynet