Last active
May 29, 2021 15:33
-
-
Save iamtodor/eb7f02fc9571cc705774408a474d5dcb to your computer and use it in GitHub Desktop.
Disk caching in Picasso with OkHttp interceptors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// module level build.gradle dependencies | |
compile 'com.squareup.picasso:picasso:2.5.2' | |
compile 'com.squareup.okhttp3:okhttp:3.4.2' | |
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.0.2' | |
// imports | |
import com.jakewharton.picasso.OkHttp3Downloader; | |
import com.squareup.picasso.Picasso; | |
import java.io.IOException; | |
import okhttp3.Cache; | |
import okhttp3.Interceptor; | |
import okhttp3.OkHttpClient; | |
import okhttp3.Response; | |
// getter | |
private Picasso getPicasso() { | |
OkHttpClient okHttpClient1 = new OkHttpClient.Builder() | |
.addInterceptor(new Interceptor() { | |
@Override | |
public Response intercept(Chain chain) throws IOException { | |
Response originalResponse = chain.proceed(chain.request()); | |
return originalResponse.newBuilder().header("Cache-Control", "max-age=" + (60 * 60 * 24 * 365)) | |
.build(); | |
} | |
}) | |
.cache(new Cache(MainActivity.this.getCacheDir(), Integer.MAX_VALUE)) | |
.build(); | |
OkHttp3Downloader downloader = new OkHttp3Downloader(okHttpClient1); | |
Picasso picasso = new Picasso.Builder(this).downloader(downloader).build(); | |
Picasso.setSingletonInstance(picasso); | |
return picasso; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment