2011-09-22 69 views
1

其實我已經使用下面的代碼來檢查wifi是否活動(其工作正常)。 我只是想確認我可以使用相同的代碼來檢查3G激活狀態:如何在我的應用程序中檢查3G的狀態:

public boolean checkwifi() 
    { 
     ConnectivityManager connec = (ConnectivityManager) this.getSystemService(this.CONNECTIVITY_SERVICE); 
     android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
     android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 

     // Here if condition check for wifi and mobile network is available or not. 
     // If anyone of them is available or connected then it will return true, otherwise false; 

     if (wifi.isConnected()) { 
      return true; 
     } 
     else if (mobile.isConnected()) { 
      return true; 
     } 
     return false; 
    } 
+0

當您在手機上運行該代碼時會發生什麼?如果它給出正確的結果,那麼你可以使用它。 –

+0

希望這有助於http://stackoverflow.com/questions/3262781/how-to-check-wifi-or-3g-network-is-available-on-android-device和這個http://stackoverflow.com/questions/2919414 /獲得網絡類型 – dpp

回答

0

檢查您的連接(WIFI或移動)開啓或關閉,請嘗試以下操作:

boolean connected = false; 
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); 
    if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED || 
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTING || 
      connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED || 
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTING) { 
     //we are connected to a network 

     connected = true; 
    } 
    else 
     connected = false; 
0

是 - 該代碼應工作。我有你可能需要的功能額外位來實現:

public static boolean isOnline(Context context) { 
    //ConnectivityManager is used to check available network(s) 
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    return cm.getActiveNetworkInfo() != null; 
} 

這確實與您的代碼 - 它會告訴你,如果你是在網上通過任何方式(3G或WiFi),但它是一個一點更簡潔。

**編輯**

下面是該方法的源 - 如果沒有活動的網絡連接,將返回null或將返回NetworkInfo對象的當前連接:

/** 
* Return NetworkInfo for the active (i.e., connected) network interface. 
* It is assumed that at most one network is active at a time. If more 
* than one is active, it is indeterminate which will be returned. 
* @return the info for the active network, or {@code null} if none is active 
*/ 
public NetworkInfo getActiveNetworkInfo() { 
    enforceAccessPermission(); 
    for (NetworkStateTracker t : mNetTrackers) { 
     NetworkInfo info = t.getNetworkInfo(); 
     if (info.isConnected()) { 
      return info; 
     } 
    } 
    return null; 
} 
+0

「通過任何方法」,因此它包括GPRS(2.5G)和EDGE(2.75G)。我錯了嗎? –

+0

查看修改後的答案 - 是的,這適用於任何連接類型。 – Martyn

相關問題