使用okhttp Interceptor检查网络连接性 [英] Using okhttp Interceptor to check the network connectitivty
问题描述
我们可以使用拦截器来检查网络连接并在仅连接的情况下继续进行吗?
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");
}
}
}
更新说明:
此外,定位到Android 7.0及更高版本的应用必须使用registerReceiver(BroadcastReceiver,IntentFilter)注册CONNECTIVITY_ACTION广播.在清单中声明接收者无效.
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
这篇关于使用okhttp Interceptor检查网络连接性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!