【发布时间】:2017-12-19 15:40:01
【问题描述】:
我是 Android 新手,我正在尝试找出在用户没有网络连接时处理这种情况的最佳方法。我正在使用带有 OkHttp 的 Retrofit2,并且我尝试了多种解决方案。
第一种方法:
OkHttp 拦截器:
new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// try the request
Response response = chain.proceed(request);
private final SuperActivityToast warningToast = new
SuperActivityToast(currentActivity, new Style(), Style.TYPE_BUTTON).setIndeterminate(true);
warningToast.setText("Currently offline").show;
while (!response.isSuccessful()) {
// retry the request
response = chain.proceed(request);
}
// otherwise just pass the original response on
return response;
}
}
所以基本上我一直重试请求,直到用户有网络连接(这是基本思想,我将实施检查以区分用户没有网络的情况和问题来自服务器的情况) ,但我知道它效率不高。也永远不会访问while循环(我使用带有断点的调试模式来检查),代码停止在:Response response = chain.proceed(request);,在这部分请求被重新加载,即使它再次失败,拦截器也永远不会重新访问,控制台中没有任何错误。
第二种方法:
我使用了这个例子:Retrying the request using Retrofit 2 实现了一个带有按钮的 toast,供用户手动重试失败的请求,但在这种情况下我遇到了一个障碍:如果一个活动有多个请求,一个 toast将显示一个重试按钮,供用户单独重试每个请求。
还有什么我错过的方式吗?主要问题是:检查用户网络断开并允许用户重试请求或让我们自动重试失败请求的最佳方法是什么?
【问题讨论】:
-
如果对你有帮助,请查看我的回答
标签: android retrofit2 okhttp android-networking