Using okhttp Interceptor to check the network connectitivty

試著忘記壹切 提交于 2020-01-16 06:18:12

问题


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

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


回答1:


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

Manifest:

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

The BroadcastReceiver itself:

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

Update note:

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.

See the docs for other options



来源:https://stackoverflow.com/questions/28806044/using-okhttp-interceptor-to-check-the-network-connectitivty

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!