Reputation: 12615
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.
Upvotes: 1
Views: 1968
Reputation: 2817
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");
}
}
}
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
Upvotes: 1