2010-11-03 208 views
22

我有以下代碼用於檢查我的應用程序上的互聯網連接WiFi/EDGE/GPRS/3G。在Android上檢查互聯網連接

代碼

public static boolean checkConn(Context ctx) { 
    ConnectivityManager conMgr = (ConnectivityManager) ctx 
      .getSystemService(Context.CONNECTIVITY_SERVICE); 
    if (conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED 
     || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING) { 
     return true; 
    } else if (conMgr.getNetworkInfo(0).getState()==NetworkInfo.State.DISCONNECTED 
     || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED){ 
     return false; 
    } 
    return false; 
} 

,我稱之爲象下面這樣:

if (CheckInternet.checkConn(introPage.this) == true) { 
    Intent toMainPage = new Intent(introPage.this, mainPage.class); 
    System.gc(); 
    startActivity(toMainPage); 
} else if (CheckInternet.checkConn(getApplicationContext()) == false) { 
    Toast.makeText(getApplicationContext(), 
     "Sorry, No internet connectivity found", Toast.LENGTH_SHORT) 
      .show(); 
} 

,但我有一個問題,就是如果我連接到無線網絡,我打開應用程序,它工作正常,但如果我關閉應用程序,並關閉WiFi並重新打開應用程序,它不會通過「無連接」的錯誤,我需要關閉我的設備,然後打開它,同樣的情況下如果WiFi關閉,我打開應用程序,它會拋出「無連接」的錯誤,如果我打開它,仍然會拋出與「無連接」相同的錯誤,除非我關閉設備。

+0

關閉應用..表兄弟姐妹如果u按HME關閉它,然後應用程序會在後臺和OnCreate中不會被解僱 – DeRagan 2010-11-03 10:41:21

+0

@Rahul,但爲什麼即使打開wifi,它仍然沒有連接問題? – kaibuki 2010-11-03 10:43:47

+0

我不知道你在哪裏調用這一行代碼...如果你只是檢查這個條件下的活動創建它將只被稱爲一次... – DeRagan 2010-11-03 10:48:58

回答

68

有時活動連接不是列表中的第一個,或者不活動或處於錯誤狀態。這是我會怎麼做:

NetworkInfo i = conMgr.getActiveNetworkInfo(); 
    if (i == null) 
    return false; 
    if (!i.isConnected()) 
    return false; 
    if (!i.isAvailable()) 
    return false; 
    return true; 

[編輯1]不要忘了在應用程序清單中添加該權限:

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

這是否幫助你嗎?

靈光

+0

我一直在尋找互聯網檢查在Android上連接並找到您的答案。它看起來簡單而好看。但它也檢查3G嗎?謝謝。 – lomza 2011-09-21 13:31:59

+2

您必須檢查網絡的類型。 i.getType()== ConnectivityManager.TYPE_MOBILE,你甚至可以獲得子類型。 i.getSubType()== TelephonyManager.NETWORK_TYPE_ * – Emmanuel 2011-09-21 14:50:30

+0

你也可以使用ConnectivityManager ==> http://stackoverflow.com/a/4009133/186636 – 2012-04-13 19:05:13

2

更好:

if (conMgr != null) { 
    NetworkInfo i = conMgr.getActiveNetworkInfo(); 
    if (i != null) { 
     if (!i.isConnected()) 
      ret = false; 
     if (!i.isAvailable()) 
      ret = false;     
    } 

    if (i == null) 
     ret = false; 

} else 
    ret = false; 

與其他形式,如果 「網絡I」 等於空,然後,檢查後!i.isConnected()一定會失敗(我爲空)。

+0

爲什麼不用黑色方法而不是白色方法? – 2012-02-13 07:27:01

+0

你錯了,在其他形式「if(i == null)」將「返回false」,所以跳過所有其餘的檢查。同樣在另一種方式,有較少的CC(較少的幫助) – NicoGranelli 2012-02-17 20:46:00

+0

'返回'優於'使用'其他' ('其他'給予癌症) – SparK 2013-06-19 18:39:37

2
public static boolean checkNetworkStatus(Context context) { 
    ConnectivityManager connectivity = (ConnectivityManager) context 
      .getSystemService(Context.CONNECTIVITY_SERVICE); 
    TelephonyManager telephony = (TelephonyManager) context 
      .getSystemService(Context.TELEPHONY_SERVICE); 
    NetworkStatus netStatus = new NetworkStatus(connectivity, telephony); 
    if (netStatus.isNetworkAvailable() == true) { 
     Log.e(" in checkNetworkStatus()", "network available"); 
     return true; 
    } else { 
     Log.e(" in checkNetworkStatus()", "no network"); 
     return false; 
    } 
} 

wifi-


void chkStatus() { 
    final ConnectivityManager connMgr = (ConnectivityManager) this 
      .getSystemService(Context.CONNECTIVITY_SERVICE); 
    final android.net.NetworkInfo wifi = connMgr 
      .getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
    final android.net.NetworkInfo mobile = connMgr 
      .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 
    if (wifi.isAvailable()) { 
     Toast.makeText(this, "Wifi", Toast.LENGTH_LONG).show(); 
    } else if (mobile.isAvailable()) { 
     Toast.makeText(this, "Mobile 3G ", Toast.LENGTH_LONG).show(); 
    } else { 
     Toast.makeText(this, "No Network ", Toast.LENGTH_LONG).show(); 
    } 
} 
0

喜試試下面的代碼:

public class NetworkCheckDemo extends Activity 
{ 
TextView tvstatus; 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    tvstatus=(TextView)findViewById(R.id.txtviewstatus); 
    ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo nf=cn.getActiveNetworkInfo(); 
    if(nf != null && nf.isConnected()==true) 
    { 
     Toast.makeText(this, "Network Available", Toast.LENGTH_LONG).show(); 
     tvstatus.setText("Network Available"); 
    } 
    else 
    { 
     Toast.makeText(this, "Network Not Available", Toast.LENGTH_LONG).show(); 
     tvstatus.setText("Network Not Available"); 
     } 
    } 
    } 

添加以下3級權限的Android清單文件。

<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> 
+2

「CHANGE_NETWORK_STATE」不是必要的 – njzk2 2013-12-04 21:30:04

0

我來檢查,如果我有連接,不要忘記檢查的NetworkInfo爲空或不是,因爲在未進行TYPE_MOBILE返回NULL提供的移動數據連接,該平板電腦的NetworkInfo。

public static boolean collectionAllowed(Context context) { 
    ConnectivityManager connectivityManager = (ConnectivityManager) context 
      .getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo mobileInfo = connectivityManager.getNetworkInfo(
      ConnectivityManager.TYPE_MOBILE); 
    State mobile = NetworkInfo.State.DISCONNECTED; 
    if (mobileInfo != null) { 
     mobile = mobileInfo.getState(); 
    } 
    NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(
      ConnectivityManager.TYPE_WIFI); 
    State wifi = NetworkInfo.State.DISCONNECTED; 
    if (wifiInfo != null) { 
     wifi = wifiInfo.getState(); 
    } 
    boolean dataOnWifiOnly = (Boolean) PreferenceManager 
      .getDefaultSharedPreferences(context).getBoolean(
        "data_wifi_only", true); 
    if ((!dataOnWifiOnly && (mobile.equals(NetworkInfo.State.CONNECTED) || wifi 
      .equals(NetworkInfo.State.CONNECTED))) 
      || (dataOnWifiOnly && wifi.equals(NetworkInfo.State.CONNECTED))) { 
     return true; 
    } else { 
     return false; 
    } 
} 
3

簡短的回答:

public boolean isNetworkAvailable() { 
    ConnectivityManager connectivityManager = (ConnectivityManager)getActivity().getApplicationContext() 
               .getSystemService(Context.CONNECTIVITY_SERVICE); 

    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); 
    return activeNetworkInfo != null; 
} 
1

試試這個:

public boolean isInternetAvailable(Context context) { 
     ConnectivityManager conMgr = (ConnectivityManager) context 
       .getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo i = conMgr.getActiveNetworkInfo(); 
      if (i == null) 
      return false; 
      if (!i.isConnected()) 
      return false; 
      if (!i.isAvailable()) 
      return false; 
      return true; 

    } 

與此權限:

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

0

一樣的批准的答案,但在短期:

public static boolean isNetworkAvailable(Context context) { 
    ConnectivityManager cm = (ConnectivityManager) 
      context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo info = cm.getActiveNetworkInfo(); 
    return info != null && info.isConnected() && info.isAvailable(); 
} 
0

您可以使用此真棒gist by emil2k:按家庭或返回鍵

import android.content.Context; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 
import android.telephony.TelephonyManager; 

public class Connectivity { 
    public static NetworkInfo getNetworkInfo(Context context){ 
     ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
     return cm.getActiveNetworkInfo(); 
    } 

    public static boolean isConnected(Context context){ 
     NetworkInfo info = Connectivity.getNetworkInfo(context); 
     return (info != null && info.isConnected()); 
    } 

    public static boolean isConnectedWifi(Context context){ 
     NetworkInfo info = Connectivity.getNetworkInfo(context); 
     return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI); 
    } 

    public static boolean isConnectedMobile(Context context){ 
     NetworkInfo info = Connectivity.getNetworkInfo(context); 
     return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE); 
    } 

    public static boolean isConnectedFast(Context context){ 
     NetworkInfo info = Connectivity.getNetworkInfo(context); 
     return (info != null && info.isConnected() && Connectivity.isConnectionFast(info.getType(),info.getSubtype())); 
    } 

    public static boolean isConnectionFast(int type, int subType){ 
     if(type==ConnectivityManager.TYPE_WIFI){ 
      return true; 
     }else if(type==ConnectivityManager.TYPE_MOBILE){ 
      switch(subType){ 
      case TelephonyManager.NETWORK_TYPE_1xRTT: 
       return false; // ~ 50-100 kbps 
      case TelephonyManager.NETWORK_TYPE_CDMA: 
       return false; // ~ 14-64 kbps 
      case TelephonyManager.NETWORK_TYPE_EDGE: 
       return false; // ~ 50-100 kbps 
      case TelephonyManager.NETWORK_TYPE_EVDO_0: 
       return true; // ~ 400-1000 kbps 
      case TelephonyManager.NETWORK_TYPE_EVDO_A: 
       return true; // ~ 600-1400 kbps 
      case TelephonyManager.NETWORK_TYPE_GPRS: 
       return false; // ~ 100 kbps 
      case TelephonyManager.NETWORK_TYPE_HSDPA: 
       return true; // ~ 2-14 Mbps 
      case TelephonyManager.NETWORK_TYPE_HSPA: 
       return true; // ~ 700-1700 kbps 
      case TelephonyManager.NETWORK_TYPE_HSUPA: 
       return true; // ~ 1-23 Mbps 
      case TelephonyManager.NETWORK_TYPE_UMTS: 
       return true; // ~ 400-7000 kbps 
      /* 
      * Above API level 7, make sure to set android:targetSdkVersion 
      * to appropriate level to use these 
      */ 
      case TelephonyManager.NETWORK_TYPE_EHRPD: // API level 11 
       return true; // ~ 1-2 Mbps 
      case TelephonyManager.NETWORK_TYPE_EVDO_B: // API level 9 
       return true; // ~ 5 Mbps 
      case TelephonyManager.NETWORK_TYPE_HSPAP: // API level 13 
       return true; // ~ 10-20 Mbps 
      case TelephonyManager.NETWORK_TYPE_IDEN: // API level 8 
       return false; // ~25 kbps 
      case TelephonyManager.NETWORK_TYPE_LTE: // API level 11 
       return true; // ~ 10+ Mbps 
      // Unknown 
      case TelephonyManager.NETWORK_TYPE_UNKNOWN: 
      default: 
       return false; 
      } 
     }else{ 
      return false; 
     } 
    } 

}