2

我必须使用 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;
}      

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

4

3 回答 3

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);
}     
于 2012-01-18T06:49:46.573 回答
1

网络可用性检查:

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
于 2018-05-08T05:32:36.650 回答
0

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

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

}

于 2021-03-03T09:10:17.690 回答