我正在使用 Retrofit 库解析 JSON 数据并将其填充到 RecyclerView 中。
但是,现在我想知道,我如何存储相同的数据以供离线使用(即使互联网不可用)。
@Override
public void onResume() {
super.onResume();
subscription = sampleAPI.getSamples()
.cache()
.timeout(5000, TimeUnit.MILLISECONDS)
.retry(1)
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
Log.d(getClass().getName(), "Called unsubscribe OnPause()");
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<SampleTypePojo>() {
@Override
public void call(SampleTypePojo jokesModel) {
sampleList = jokesModel.getValue();
displaySampleList(sampleList);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
Log.e(getClass().getName(), "ERROR: " + throwable.getMessage());
throwable.printStackTrace();
}
}
);
}
private void getSampleData() {
if (sampleAPI == null) {
sampleAPI = new RestAdapter.Builder()
.setEndpoint(Constants.BASE_URL)
.setLogLevel(RestAdapter.LogLevel.FULL)
.build()
.create(SampleAPI.class);
}
}
应用级别: build.gradle
dependencies {
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'io.reactivex:rxjava:1.0.4'
compile 'io.reactivex:rxandroid:0.24.0'
}
最佳答案
让我们首先构建一个 OKHTTP 客户端
缓存 检查连接的拦截器,如果没有则请求缓存数据: 这是客户端。
OkHttpClient client = new OkHttpClient
.Builder()
.cache(new Cache(App.sApp.getCacheDir(), 10 * 1024 * 1024)) // 10 MB
.addInterceptor(new Interceptor() {
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (App.isNetworkAvailable()) {
request = request.newBuilder().header("Cache-Control", "public, max-age=" + 60).build();
} else {
request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build();
}
return chain.proceed(request);
}
})
.build();
我们首先创建 10 MB 的缓存对象,从静态应用程序上下文中获取缓存目录。
然后拦截器使用我的应用程序类中的实用方法来检查连接性。如果存在连接,我们会告诉请求它可以重复使用数据 60 秒。
如果没有连接,我们要求只提供(仅缓存)7 天前的“陈旧”数据。
现在让这个 OkHTTP 客户端成为 Retrofit2 的客户端,当应用程序离线时,您将能够使用旧的缓存数据
关于android - 改造缓存数据以供离线使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43133147/