okhttp 无网络 Interceptor内部闪退
时间: 2023-09-17 11:09:55 浏览: 68
OkHttp 拦截器内部闪退可能是因为在拦截器中没有判断网络是否可用导致的。在无网络连接的情况下,你可以在拦截器中使用 `ConnectivityManager` 类来检测网络连接状态,例如:
```java
public class NetworkInterceptor implements Interceptor {
private Context mContext;
public NetworkInterceptor(Context context) {
mContext = context;
}
@Override
public Response intercept(Chain chain) throws IOException {
if (!isConnected()) {
throw new NoNetworkException();
}
// 继续执行请求
Request request = chain.request();
return chain.proceed(request);
}
private boolean isConnected() {
ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
return info != null && info.isConnected();
}
}
```
在上述拦截器中,我们通过 `ConnectivityManager` 类检测网络连接状态,如果没有网络连接则抛出自定义的 `NoNetworkException` 异常。这样就可以在拦截器中避免无网络时的闪退问题。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)