• Android 通用獲取IP的方法

    1
    Android Java C/C++ 28728 次瀏覽
    大家好,我們這一節講一下,Android獲取Ip的一些方法,在我們開發中,有判斷手機是否聯網,或者想獲得當前手機的Ip地址,當然WIFI連接的和
    我們3G卡的Ip地址當然是不一樣的.
    以這種方法不可取!
    首先我嘗試了如下方法:
    WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); 
    WifiInfo wifiInfo = wifiManager.getConnectionInfo(); 
    int ipAddress = wifiInfo.getIpAddress(); 
    當我的手機處于飛行狀態是,獲得Ip地址為空,剛好符合要求!!!
    最后查了一些資料,發現如下方法是比較通用的,我嘗試了WIFI和G3卡,都獲取了正確的Ip地址代碼如下:
    public String getLocalIpAddress() { 
      try { 
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { 
          NetworkInterface intf = en.nextElement(); 
          for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { 
            InetAddress inetAddress = enumIpAddr.nextElement(); 
            if (!inetAddress.isLoopbackAddress()) { 
            return inetAddress.getHostAddress().toString(); 
          } 
        } 
      } 
      } catch (SocketException ex) { 
          Log.e(LOG_TAG, ex.toString()); 
      } 
      return null; 
    } 
    當我的手機處于飛行狀態是,獲得Ip地址為空,剛好符合要求!!!

    相似問題

    相關經驗

    相關資訊

    相關文檔

  • sesese色