1 獲取ConnecttiveManager對象java
Context context = activity.getApplicationContext(); ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2 獲取所有的NetworkInfo:android
注:因爲getAllNetworkInfo這個方法在SDK版本23中已經被棄用,就用getAllNetworks方法代替,可是因爲getAllNetworks方法是在版本21中才添加的,因此首先判斷手機的SDK版本信息,若是是21以上的手機就用getAllNetworks方法,反之就只能繼續用getAllNetworkInfo方法了ui
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { Network[] networks = connectivityManager.getAllNetworks(); if (networks != null && networks.length > 0) { int size = networks.length; for (int i=0; i<size; i++) { Log.d("TAG", "=====狀態====" + connectivityManager.getNetworkInfo(networks[i]).getState()); Log.d("TAG", "=====類型====" + connectivityManager.getNetworkInfo(networks[i]).getTypeName()); if (connectivityManager.getNetworkInfo(networks[i]).getState() == NetworkInfo.State.CONNECTED) { return true; } } } } else { NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo(); if (networkInfos != null && networkInfos.length > 0) { int size = networkInfos.length; for (int i=0; i<size; i++) { Log.d("TAG", "=====狀態====" + networkInfos[i].getState()); Log.d("TAG", "=====類型====" + networkInfos[i].getTypeName()); if (networkInfos[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } }