Android开发(七)——判断网络状态
生活随笔
收集整理的這篇文章主要介紹了
Android开发(七)——判断网络状态
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
項目中難免會出現(xiàn)使用網(wǎng)絡(luò)的情況,使用網(wǎng)絡(luò)前得進行網(wǎng)絡(luò)判斷,看網(wǎng)上的網(wǎng)友一般有多種實現(xiàn)版本。
第一種:
// 是否有網(wǎng)絡(luò)連接public static boolean isNetworkConnected() {if (App.getContext() != null) {ConnectivityManager mConnectivityManager = (ConnectivityManager) App.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();if (mNetworkInfo != null) {return mNetworkInfo.isAvailable();}}return false;}第二種:
/*** 判斷網(wǎng)絡(luò)是否可用* * @param context* @return*/public static boolean isNetworkAvailable(Context context) {ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);if (cm != null) {NetworkInfo[] info = cm.getAllNetworkInfo();if (info != null) {for (int i = 0; i < info.length; i++) {if (info[i].isConnected()) {return true;}}}}return false;}其中主要的使用區(qū)別是isConnected()與isAvailable(),參考文章[3],總結(jié)5種連接狀態(tài)情況:
| 在WLAN設(shè)置界面狀態(tài) | 輸出 |
| 顯示連接已保存,但標(biāo)題欄沒有,即沒有實質(zhì)連接上 | 輸出為:not connect, available |
| 顯示連接已保存,標(biāo)題欄也有已連接上的圖標(biāo)? | 輸出為:connect, available |
| 選擇不保存后?? | 輸出為:not connect, available |
| 選擇連接,在正在獲取IP地址時? | 輸出為:not connect, not available |
| 連接上后 | 輸出為:connect, available |
建議使用:
// 是否有網(wǎng)絡(luò)連接public static boolean isNetworkConnected() {if (App.getContext() != null) {ConnectivityManager mConnectivityManager = (ConnectivityManager) App.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();if (mNetworkInfo != null) {return mNetworkInfo.isAvailable() && mNetworkInfo.isConnected();}}return false;}?
參考:
[1] http://www.cnblogs.com/codeworker/archive/2012/04/23/2467180.html
[2] http://blog.csdn.net/heng615975867/article/details/17280227
[3] 關(guān)于NetworkInfo對象的isConnected()與isAvailable().http://www.oschina.net/question/54100_34632
轉(zhuǎn)載于:https://www.cnblogs.com/ccdc/p/4432583.html
與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的Android开发(七)——判断网络状态的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PAT-BASIC-1016-部分A+B
- 下一篇: Android Paint、Path详解