如何检查网络可用性?

时间:2011-09-13 16:01:48

标签: android wifi gprs

我必须使用wifi(如果可用)将我的应用程序与服务器连接, 或者gprs(如果wifi不可用)。 这是我检查连接可用性的代码

public static final boolean isConnectionAvailable(Activity a)
{  

  ConnectivityManager cm = (ConnectivityManager)a.getSystemService(Context.CONNECTIVITY_SERVICE);

  State mobile = cm.getNetworkInfo(0).getState();

  State wifi = cm.getNetworkInfo(1).getState();

  if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING)
    {
        return true;
    }
  if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING)
    {
        return true;
    }

   return false;
}      

这是正确的方法吗?谁能建议我一个更好的方法?

3 个答案:

答案 0 :(得分:9)

以下非常类似的方法可行,但具有不关心底层媒体的额外优势,因为它看起来好像不仅仅支持WiFi。也许这些也被手机覆盖,但文档并不是非常明确:

// 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);
}     

答案 1 :(得分:0)

网络可用性检查:

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

答案 2 :(得分:0)

或者你可以使用一些 kotlin 实现

fun Context.isNetworkAvailable(): Boolean {
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
return activeNetwork?.isConnectedOrConnecting == true

}