最近作項目的時候須要獲取android設備地址,在網上找到了以下的方式html
方式一:java
[java] view plaincopyandroid
import java.net.InetAddress; app
import java.net.NetworkInterface; oop
import java.net.SocketException; 測試
import java.util.Enumeration; spa
//不適用android較新版本(例如4.0等) .net
public String getLocalIpAddress() { orm
try { htm
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) {
System.out.println(ex.toString());
}
return null;
}
可是通過測試該方法在android2.3, 2.2...較老版本有效,可是在android較新版本(例如4.0等)獲取的數據不正確。
方式二: 經過WifiManager, DhcpInfo獲取IP地址以及網關等信息(在android4.0等版本也適用)
[java] view plaincopy
package com.jason.demo.androidip;
import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.format.Formatter;
public class IPAddress {
public String getIPAddress(Context ctx){
WifiManager wifi_service = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcpInfo = wifi_service.getDhcpInfo();
WifiInfo wifiinfo = wifi_service.getConnectionInfo();
System.out.println("Wifi info----->"+wifiinfo.getIpAddress());
System.out.println("DHCP info gateway----->"+Formatter.formatIpAddress(dhcpInfo.gateway));
System.out.println("DHCP info netmask----->"+Formatter.formatIpAddress(dhcpInfo.netmask));
//DhcpInfo中的ipAddress是一個int型的變量,經過Formatter將其轉化爲字符串IP地址
return Formatter.formatIpAddress(dhcpInfo.ipAddress);
}
}
加入permission
[html] view plaincopy
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>