Android編程判斷網(wǎng)絡(luò)連接是否可用的方法
本文實例講述了Android編程判斷網(wǎng)絡(luò)連接是否可用的方法。分享給大家供大家參考,具體如下:
為了提高用戶體驗,我們在開發(fā) android 應(yīng)用的過程需要聯(lián)網(wǎng)獲取數(shù)據(jù)的時候我們首先要做的一步就是:
1.判斷當(dāng)前手機(jī)是否打開了網(wǎng)絡(luò)
2.打開了網(wǎng)絡(luò)是否可以上網(wǎng)
然后再去執(zhí)行聯(lián)網(wǎng)邏輯,避免沒聯(lián)網(wǎng)做不必要的工作!
通常情況下,我們是這樣判斷的
public static boolean isNetAvailable(Context context) { ConnectivityManager connectManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); return (connectManager.getActiveNetworkInfo() != null); }
但是這樣只完成了第一步,判斷網(wǎng)絡(luò)是否打開,
注意:打開并不代表就可以上網(wǎng),
觀察發(fā)現(xiàn) NetworkInfo 有一個方法:
官方的解釋是
Indicates whether network connectivity is possible. A network is unavailable when a persistent or semi-persistent condition prevents the possibility of connecting to that network. Examples include
The device is out of the coverage area for any network of this type.
The device is on a network other than the home network (i.e., roaming), and data roaming has been disabled.
The device's radio is turned off, e.g., because airplane mode is enabled.
Returns:
true if the network is available, false otherwise
他列舉了幾種網(wǎng)絡(luò)已連接但不可以上網(wǎng)的情況,
所以我們這樣改改就好了:
public static boolean isNetAvailable(Context context) { ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); return (info != null && info.isAvailable()); }
希望本文所述對大家Android程序設(shè)計有所幫助。
- Android 判斷網(wǎng)絡(luò)狀態(tài)實例詳解
- Android中判斷網(wǎng)絡(luò)是否連接實例詳解
- Android中利用NetworkInfo判斷網(wǎng)絡(luò)狀態(tài)時出現(xiàn)空指針(NullPointerException)問題的解決方法
- Android編程判斷網(wǎng)絡(luò)是否可用及調(diào)用系統(tǒng)設(shè)置項的方法
- Android中判斷網(wǎng)絡(luò)連接狀態(tài)的方法
- Android判斷網(wǎng)絡(luò)類型的方法(2g,3g還是wifi)
- Android中判斷網(wǎng)絡(luò)是否可用的代碼分享
- Android中監(jiān)聽判斷網(wǎng)絡(luò)連接狀態(tài)的方法
- Android中判斷網(wǎng)絡(luò)連接是否可用及監(jiān)控網(wǎng)絡(luò)狀態(tài)
- Android 判斷網(wǎng)絡(luò)狀態(tài)及開啟網(wǎng)路
相關(guān)文章
android實現(xiàn)banner輪播圖無限輪播效果
這篇文章主要為大家詳細(xì)介紹了android實現(xiàn)banner輪播圖無限輪播效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10Android 中為什么要用Fragment.setArguments(Bundle bundle)來傳遞參數(shù)
這篇文章主要介紹了Android 中為什么要用Fragment.setArguments(Bundle bundle)來傳遞參數(shù),非常不錯,具有參考借鑒價值,需要的朋友參考下2017-01-0130分鐘搞清楚Android Touch事件分發(fā)機(jī)制
30分鐘搞清楚Android Touch事件分發(fā)機(jī)制,Touch事件分發(fā)中只有兩個主角:ViewGroup和View,想要深入學(xué)習(xí)的朋友可以參考本文2016-03-03Android實現(xiàn)從底部彈出的Dialog的實例代碼
這篇文章主要介紹了Android實現(xiàn)從底部彈出的Dialog的實例代碼,非常不錯,具有參考借鑒價值 ,需要的朋友可以參考下2018-04-04