Occurred on Desire API 2.2
當關閉行動網路時,透過以下的方法判斷是否有網路,卻回傳 true?!
public static boolean isNetworkAvailable(Context context) { ConnectivityManager connectivity = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity == null) { } else { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; }若使用飛安模式則是回傳 false,但此情況僅出現幾次, 之後則模擬不出來,所以是否有疑漏其他操作行為?
Solution
在 API 2.1, 2.2, 2.3.3 的手機上測以下三種模式下所對應的結果:
飛安模式
- NetworkInfo: [Landroid.net.NetworkInfo;@xxxxx,
- activeInfo: null
- type: MOBILE, state: DISCONNECTED, detailed state: DISCONNECTED, isAvailable: false, isConnected: false
- 其他 type 的 values 皆為以下
- state: UNKNOWN, detailed state: IDLE, isAvailable: false, isConnected: false
開啟行動網路
- NetworkInfo: [Landroid.net.NetworkInfo;@xxxx,
- activeInfo: NetworkInfo: type: MOBILE[UMTS], state: CONNECTED/CONNECTED, reason: dataEnabled, extra: internet, roaming: false, failover: false, isAvailable: true
- type: MOBILE, state: CONNECTED, detailed state: CONNECTED, isAvailable: true
- 其他 type 的 values 則為以下
- state: UNKNOWN or DISCONNECTED, detailed state: IDLE/DISCONNECTED/CONNECTED, isAvailable: true(few types are true), isConnected: false(few types are true)
關閉行動網路
- NetworkInfo: [Landroid.net.NetworkInfo;@444b0530,
- activeInfo: null
- type: MOBILE, state: DISCONNECTED, detailed state: DISCONNECTED, isAvailable: true, isConnected: false
- 其他 type 的 values 皆為以下
- state: UNKNOWN/DISCONNECTED, detailed state: IDLE/DISCONNECTED, isAvailable: true(few types are false), isConnected: false
所以 state 結果應該和我們的需求一致 ,因此猜測是否得到的是狀態正在轉換時的值,試著監聽網路狀態的改變,以下方式能得到和操作一致的結果,但不確定此種方式是否正確。
// briefly TelephonyManager.listen(new PhoneStateListener() { @Override public void onDataConnectionStateChanged(int state) { switch(state){ case TelephonyManager.DATA_DISCONNECTED: break; case TelephonyManager.DATA_CONNECTING: break; case TelephonyManager.DATA_CONNECTED: break; } } }, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);另一種則是 onReceiver action "android.net.conn.CONNECTIVITY_CHANGE"
但在改變任何狀態時皆收不到相關的 action!!!?
Pending Issues
監聽網路狀態 Using receiver to listen action "android.net.conn.CONNECTIVITY_CHANGE"
* Reference
- Android – 判斷手機是否連上網路 (ConnectivityManager)
- network: android 网络判断 **
- android之ConnectivityManager简介,网络连接状态
- NetworkInfo - ConnectivityManager
- 网络连接状态的监听和判断(android,wifi,Gprs)
- Android判断网络状态方法详解
- 监听手机的网络连接状态
沒有留言:
張貼留言