搜尋此網誌

2011年12月15日

Android 檢查網路連線的兩個方法

一個是用 NetworkInfo isConnected,一個是用 ConnectivityManager getNetworkInfo(?).getState()

private void conditionCheck() {
        
         try {
              ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
             
              NetworkInfo activeNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
              if (activeNetwork.isConnected())
                  Log.w(name, "1 ok");
              else
                  Log.w(name, "1 fail");
             
              NetworkInfo activeNetwork1 = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
              if (activeNetwork1.isConnected())
                  Log.w(name, "2 ok");
              else
                  Log.w(name, "2 fail");
                           
              if ((cm.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED))
                  Log.w(name, "Mobile network is ok");
              else
                  Log.w(name, "Mobile network is fail");
             
              if ((cm.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED))
                  Log.w(name, "WiFi network is ok");  
              else
                  Log.w(name, "WiFi network is fail");
         } catch(Exception e) {
              e.printStackTrace();
         }
     }

但是以下這段卻不 work…還不知道為什麼
if ((cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.DISCONNECTED)
                       && (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.DISCONNECTED))
Log.w(name, "Cannot reach the pattern!");

沒有留言:

張貼留言