Square 在 Android 中的 Picasso 重试机制
Square's Picasso Retry Mechanism in Android
Picasso 是否有从网络下载图片失败时的重试机制?
我在他们的网站上注意到他们提到重试 3 次,直到显示错误占位符。
我目前不使用占位符(不是因为错误,也不是在等待图片下载时)。
有没有办法在构建 Picasso 对象时自己配置它?
我正在使用 Picasso.with(...).load(...).into(...) 生成器。
重试不是由 Picasso 完成的,而是由执行下载请求的 http 客户端完成的。如果您使用默认 OkHttpDownloader
,您的客户端必须为 OkHttpClient
设置重试标志,即 okHttpClient.setRetryOnConnectionFailure(true)
。
或者,使用Interceptor
并计算重试次数,直到请求成功执行。
我在这里写了一个辅助函数,希望对你有帮助
你可以去看看,MAX_RETRY_TIME。
在"interceptors"中添加重试过程
最简单的方法是将 interceptor
添加到您的 okhttpclient
,然后在您的应用程序 class[=15] 中设置 picasso
的 singleton
=]
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
int tryCount = 0;
while (!response.isSuccessful() && tryCount < 5) {
tryCount++;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
response = chain.proceed(request);
}
return response;
}
})
.build();
Picasso picasso = new Picasso
.Builder(this)
.downloader(new OkHttp3Downloader(okHttpClient))
.build();
Picasso.setSingletonInstance(picasso);
Picasso 是否有从网络下载图片失败时的重试机制?
我在他们的网站上注意到他们提到重试 3 次,直到显示错误占位符。
我目前不使用占位符(不是因为错误,也不是在等待图片下载时)。
有没有办法在构建 Picasso 对象时自己配置它?
我正在使用 Picasso.with(...).load(...).into(...) 生成器。
重试不是由 Picasso 完成的,而是由执行下载请求的 http 客户端完成的。如果您使用默认 OkHttpDownloader
,您的客户端必须为 OkHttpClient
设置重试标志,即 okHttpClient.setRetryOnConnectionFailure(true)
。
或者,使用Interceptor
并计算重试次数,直到请求成功执行。
我在这里写了一个辅助函数,希望对你有帮助
你可以去看看,MAX_RETRY_TIME。
在"interceptors"中添加重试过程
最简单的方法是将 interceptor
添加到您的 okhttpclient
,然后在您的应用程序 class[=15] 中设置 picasso
的 singleton
=]
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
int tryCount = 0;
while (!response.isSuccessful() && tryCount < 5) {
tryCount++;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
response = chain.proceed(request);
}
return response;
}
})
.build();
Picasso picasso = new Picasso
.Builder(this)
.downloader(new OkHttp3Downloader(okHttpClient))
.build();
Picasso.setSingletonInstance(picasso);