public static InetAddress getWifiIp()
{
Context myContext = Globals.getContext();
if (myContext == null)
{
throw new NullPointerException("Global context is null");
}
WifiManager wifiMgr = (WifiManager) myContext.getSystemService(Context.WIFI_SERVICE);
if (isWifiEnabled())
{
int ipAsInt = wifiMgr.getConnectionInfo().getIpAddress();
if (ipAsInt == 0)
{
return null;
}
else
{
return Util.intToInet(ipAsInt);
}
}
else
{
return null;
}
}
public static boolean isWifiEnabled()
{
Context myContext = Globals.getContext();
if (myContext == null)
{
throw new NullPointerException("Global context is null");
}
WifiManager wifiMgr = (WifiManager) myContext.getSystemService(Context.WIFI_SERVICE);
if (wifiMgr.getWifiState() == WifiManager.WIFI_STATE_ENABLED)
{
return true;
}
else
{
return false;
}
}
2、创建服务器套接字 listenSocket, 端口号可以自定义
listenSocket = new ServerSocket();
listenSocket.setReuseAddress(true);
listenSocket.bind(new InetSocketAddress(port));
3、用子线程TcpListener封装 listenSocket
while (!shouldExit)
{
if (acceptWifi)
{
if (wifiListener != null)
{
if (!wifiListener.isAlive())
{
myLog.l(Log.DEBUG, "Joining crashed wifiListener thread");
try
{
wifiListener.join();
}
catch (InterruptedException e)
{
}
wifiListener = null;
}
}
if (wifiListener == null)
{
// Either our wifi listener hasn't been created yet, or has
// crashed,
// so spawn it
wifiListener = new TcpListener(listenSocket, this);
wifiListener.start();
}
}
}