日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > Android >内容正文

Android

Android开发(七)——判断网络状态

發(fā)布時間:2025/3/13 Android 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。