//首先要开启wifi使用权限
public class GetIPlocation {
public static String getIp(Context context ) {
String ip;
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//判断wifi是否开启
if (wifiManager.isWifiEnabled()) {
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
ip = intToIp(ipAddress);
} else {
//通过gprs获取ip
ip = getLocalIpAddress();
}
if("".equals(ip)){
return "192.168.1.1";
}
return ip;
}
private static String intToIp(int i) {
return (i & 0xFF) + "." +
((i >> 8) & 0xFF) + "." +
((i >> 16) & 0xFF) + "." +
(i >> 24 & 0xFF);
}
public static 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 e) {
e.printStackTrace();
}
return "";
}
}
在Android N 中传入的Context 必须是ApplicationContext 不能是activity的content 否则会出现内存泄漏,不会通过打包。