因此,我只是实现了一种检查连通性的方法,但是我应该对每个活动都这样做吗?有没有更简单的方法来持续检查连接性?
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return isConnected;
}
最佳答案
首先创建一个ConnectivityChangeReceiver
,如下所示:
public class ConnectivityChangeReceiver extends BroadcastReceiver {
private OnConnectivityChangedListener listener;
public ConnectivityChangeReceiver(OnConnectivityChangedListener listener) {
this.listener = listener;
}
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isConnected = activeNetInfo != null && activeNetInfo.isConnectedOrConnecting();
listener.onConnectivityChanged(isConnected);
}
public interface OnConnectivityChangedListener {
void onConnectivityChanged(boolean isConnected);
}
}
然后创建一个
BaseActivity
扩展您的所有活动:public class BaseActivity extends Activity implements OnConnectivityChangedListener {
private ConnectivityChangeReceiver connectivityChangeReceiver;
@Override
public void onCreate(Bundle savedInstanceState) {
connectivityChangeReceiver = new ConnectivityChangeReceiver(this);
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(connectivityChangeReceiver, filter);
}
@Override
public void onConnectivityChanged(boolean isConnected) {
// TODO handle connectivity change
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(connectivityChangeReceiver);
}
}
(如果不想使用
BaseActivity
,则可以在所有活动中实现OnConnectivityChangedListener
。但是在这种情况下,您必须在所有Activity
中注册接收者。)关于android - 我应该在Android的每个 Activity 中检查连接性吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30018171/