建了個交流羣:416157653,歡迎你們加入討論java
判斷手機有無網絡的方式:網絡
1. 直接獲取手機有沒有wifi或數據網絡code
/** * 有網沒網 * * @param context * @return true: 有網 false:沒網 */ public static boolean hasNetwork(Context context) { if (isWifiConnected(context)) { return true; } if (isMobileConnected(context)) { return true; } return false; }
/** *判斷wifi有沒有鏈接 *return:true:連上wifi false:未連上wifi */ public static boolean isWifiConnected(Context context) { if (context != null) { ConnectivityManager mConnectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mWiFiNetworkInfo = mConnectivityManager .getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (mWiFiNetworkInfo != null) { return mWiFiNetworkInfo.isConnected(); } } return false; }
/** *判斷數據網絡有沒有鏈接 *return:true:鏈接 false:未鏈接 */ public static boolean isMobileConnected(Context context) { if (context != null) { ConnectivityManager mConnectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mMobileNetworkInfo = mConnectivityManager .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (mMobileNetworkInfo != null) { return mMobileNetworkInfo.isConnected(); } } return false; }