How to check the network availability?

空扰寡人 提交于 2019-11-28 11:50:05

The following very similar approach works, but has the added advantage of not caring what the underlying medium, since it looks as though there is support for more than just WiFi. Maybe these are also covered by mobile, but the docs aren't super clear:

// added as an instance method to an Activity
boolean isNetworkConnectionAvailable() {  
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();     
    if (info == null) return false;
    State network = info.getState();
    return (network == NetworkInfo.State.CONNECTED || network == NetworkInfo.State.CONNECTING);
}     

Network Availability Check :

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!