本文介绍了使用okhttp Interceptor检查网络连接性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以使用拦截器来检查网络连接并在仅连接的情况下继续进行吗?

Could we use Interceptor to check the network connectivity and proceed if only it's connected?

注意:我正在谈论如何使用okhttp拦截器来统一网络连接检查.

NOTICE: I'm talking about how to use okhttp interceptors to unify the network connectivity checking.

推荐答案

您可以使用BroadcastReceiver使互联网连接发生更改时通知您的应用程序.

You can use a BroadcastReceiver to make your application be notified when there is a change in internet connectivity.

清单:

<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");
      }
   }
}

有关BroadcastReceiver

更新说明:

有关其他选项,请参见文档

See the docs for other options

这篇关于使用okhttp Interceptor检查网络连接性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 19:07