android - 使用 okhttp 拦截器检查网络连通性

标签 android okhttp

我们可以使用 Interceptor 来检查网络连接并在连接时继续吗?

注意:我说的是如何使用okhttp拦截器来统一网络连通性检测。

最佳答案

您可以使用 BroadcastReceiver 让您的应用程序在 Internet 连接发生变化时收到通知。

list :

<receiver android:name="com.example.app.ConnectivityChangeReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>

BroadcastReceiver 本身:

public class ConnectivityChangeReceiver extends BroadcastReceiver {

   @Override
   public void onReceive(Context context, Intent intent) {
      if (isOnline(context)) {
         debugIntent(intent, "grokkingandroid");
      }
   }

   private boolean isOnline(Context context) {
      ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo netInfo = cm.getActiveNetworkInfo();
      return (netInfo != null && netInfo.isConnected());
   }

   private void debugIntent(Intent intent, String tag) {
      Log.v(tag, "action: " + intent.getAction());
      Log.v(tag, "component: " + intent.getComponent());
      Bundle extras = intent.getExtras();
      if (extras != null) {
         for (String key: extras.keySet()) {
            Log.v(tag, "key [" + key + "]: " +
               extras.get(key));
         }
      }
      else {
         Log.v(tag, "no extras");
      }
   }
}

As in

More on BroadcastReceiver

更新说明:

Also, apps targeting Android 7.0 and higher must register the CONNECTIVITY_ACTION broadcast using registerReceiver(BroadcastReceiver, IntentFilter). Declaring a receiver in the manifest doesn't work.

参见 the docs其他选项

关于android - 使用 okhttp 拦截器检查网络连通性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28806044/

相关文章:

android - 改造 2 取消请求工作

java - 在okhttp中使用http2时,为什么对同一主机的多个请求不只使用一个connectoin

java - okhttp 从数组添加 post 参数

android - Firebase 数据库不提交在线数据阻塞监听器

android - 滚动 Activity 标题

android - 使用 leakcanary 2.0 alpha 2 时 list 合并失败

android - 如何注销广播接收器

android - 如何转到 fragment 中 Webview 中的上一页?

java - HTTP请求实时应用,性能技巧

java - 如何处理这个 OkHttp header 响应?