2012-04-23 255 views
0

我請與檢查互聯網連接

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和我得到我的手機上錯誤的狀態我能做什麼聯繫?

+0

你會得到什麼狀態? – MByD 2012-04-23 12:17:14

+0

(wifi.isConnected())給你假? – 2012-04-23 12:23:58

回答

1

請使用下列檢查天氣Internet連接標準方法是連接或不.....

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; 
    } 
1

。你有清單文件下面提到所需的權限...

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 
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權限。