检查互联网连接

时间:2012-04-23 12:14:34

标签: android mobile error-handling wifi

我用

检查连接
ConnectivityManager connec = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

我有wifi,我手机上的状态出错了我该怎么办?

3 个答案:

答案 0 :(得分:1)

您是否在清单文件中提供了下面提到的所需权限......

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

答案 1 :(得分:1)

请使用以下标准方法检查互联网连接是否已连接.....

public static final boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mgr = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            if (mgr != null) {
                boolean mobileNetwork = false;
                boolean wifiNetwork = false;

                NetworkInfo mobileInfo = mgr
                        .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                NetworkInfo wifiInfo = mgr
                        .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

                if (mobileInfo != null)
                    mobileNetwork = mobileInfo.isConnected();
                if (wifiInfo != null)
                    wifiNetwork = wifiInfo.isConnected();

                return (mobileNetwork || wifiNetwork);
            }
        }
        return false;
    }

答案 2 :(得分:1)

您可以尝试此代码以及Wifi和Cell数据互联网连接。

private boolean haveNetworkConnection() {
  boolean haveConnectedWifi = false;
  boolean haveConnectedMobile = false;

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
    if (ni.getTypeName().equalsIgnoreCase("WIFI"))
        if (ni.isConnected())
            haveConnectedWifi = true;
    if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
        if (ni.isConnected())
            haveConnectedMobile = true;
}
   return haveConnectedWifi || haveConnectedMobile;
}

或者您可以使用以下方法

public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) 
    getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null
// otherwise check if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
    return true;
}
return false;
}

这需要ACCESS_NETWORK_STATE权限。