大家好,我們這一節講一下,Android擷取Ip的一些方法,在我們開發中,有判斷手機是否連網,或者想獲得當前手機的Ip地址,當然WIFI串連的和
我們3G卡的Ip地址當然是不一樣的.
首先我嘗試了如下方法:
view plaincopy to clipboardprint?
- WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
- WifiInfo wifiInfo = wifiManager.getConnectionInfo();
- int ipAddress = wifiInfo.getIpAddress();
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);<br />WifiInfo wifiInfo = wifiManager.getConnectionInfo();<br />int ipAddress = wifiInfo.getIpAddress();
但是獲得的居然是一個整數,我嘗試了用些數學方法都沒有成功!,所以這種方法不可取!
最後查了一些資料,發現如下方法是比較通用的,我嘗試了WIFI和G3卡,都擷取了爭取的Ip地址:代碼如下:
view plaincopy to clipboardprint?
- 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;
- }
public String getLocalIpAddress() {<br /> try {<br /> for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {<br /> NetworkInterface intf = en.nextElement();<br /> for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {<br /> InetAddress inetAddress = enumIpAddr.nextElement();<br /> if (!inetAddress.isLoopbackAddress()) {<br /> return inetAddress.getHostAddress().toString();<br /> }<br /> }<br /> }<br /> } catch (SocketException ex) {<br /> Log.e(LOG_TAG, ex.toString());<br /> }<br /> return null;<br />}<br />
當My Phone處于飛行狀態是,獲得Ip地址為空白,剛好符合要求!!!
希望對大家有所協助!謝謝~