Android手機同時支持WIFI和3G, 判斷網絡鏈接, 判斷網絡類型(WIFI或3G).java
權限: android
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
判斷網絡鏈接ruby
/** * 判斷網絡是否可用, 在使用網絡請求是預先使用此方法進行檢查, 以節省資源. * * @return 可用狀態 */ public static boolean isNetAvailable() { Context context = App.getAppContext(); ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); return (info != null && info.isAvailable() && info.isConnected()); }
判斷網絡類型網絡
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);// 3GState mobile = conMan.getNetworkInfo(0).getState();// WIFIState wifi = conMan.getNetworkInfo(1).getState();if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) { // TODO: in mobile do something } else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) { // TODO: in wifi do something }
更加精細的網絡類型:
TelephonyManager#getNetworkType or NetworkInfo#getSubtypeNamecode