在Android wifi热点获取wifi广播地址
我正在开发一款应用程序,它使用wifi在所有使用我的应用程序的网络中的所有移动设备之间广播UDP消息。
我设法发送/接收来自许多具有外部AP的手机的数据包,这是我的路由器。
但考虑到没有AP的情况,我希望用户能够使用他们的手机的Wifi热点功能,以便他们仍然可以使用我的应用程序。 所以其中一部手机将成为wifi热点,其他所有人都将与之相连。
我需要用户通过他们自己的方式连接到WiFi。 可以连接到外部AP或所述热点。 然后,当我的应用程序启动时,它会检查手机是否连接到无线网络,并调用WifiManager.isWifiEnabled()和NetworkInfo.isConnected()。
问题是,如果我在使用热点的手机中调用这些函数,函数isConnected()将返回false。 我无法使用WifiManager.getDhcpInfo()获取广播地址。 其他连接到热点的手机可以完美地工作。 但是由于WifiManager被禁用,热点手机无法发送任何广播。
所以,我的问题是“有什么方法可以检查手机当前是否是WiFi热点?如果有,是否有任何方法可以获得其广播地址?”
首先你可以检查你的IP地址是什么:
public InetAddress getIpAddress() {
InetAddress inetAddress = null;
InetAddress myAddr = null;
try {
for (Enumeration < NetworkInterface > networkInterface = NetworkInterface
.getNetworkInterfaces(); networkInterface.hasMoreElements();) {
NetworkInterface singleInterface = networkInterface.nextElement();
for (Enumeration < InetAddress > IpAddresses = singleInterface.getInetAddresses(); IpAddresses
.hasMoreElements();) {
inetAddress = IpAddresses.nextElement();
if (!inetAddress.isLoopbackAddress() && (singleInterface.getDisplayName()
.contains("wlan0") ||
singleInterface.getDisplayName().contains("eth0") ||
singleInterface.getDisplayName().contains("ap0"))) {
myAddr = inetAddress;
}
}
}
} catch (SocketException ex) {
Log.e(TAG, ex.toString());
}
return myAddr;
}
我用这个IP以这种方式获得广播:
public InetAddress getBroadcast(InetAddress inetAddr) {
NetworkInterface temp;
InetAddress iAddr = null;
try {
temp = NetworkInterface.getByInetAddress(inetAddr);
List < InterfaceAddress > addresses = temp.getInterfaceAddresses();
for (InterfaceAddress inetAddress: addresses)
iAddr = inetAddress.getBroadcast();
Log.d(TAG, "iAddr=" + iAddr);
return iAddr;
} catch (SocketException e) {
e.printStackTrace();
Log.d(TAG, "getBroadcast" + e.getMessage());
}
return null;
}
当然可以用一种方法来完成,但在我的实现中,将它分成两种方法是有用的。
要确定Wifi Tether是否在您可以使用此代码:
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
Method[] wmMethods = wifi.getClass().getDeclaredMethods();
for (Method method: wmMethods) {
if (method.getName().equals("isWifiApEnabled")) {
try {
if ((Boolean) method.invoke(wifi)) {
isInetConnOn = true;
iNetMode = 2;
} else {
Log.d(TAG, "WifiTether off");
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
如果客户端设备需要知道服务器设备是否为移动热点,则可以使用特定的IP地址。 据我所知,所有Tethering设备都有相同的地址192.168.43.1它在Android 2.3和4.上是一样的。+,在许多手机和平板电脑上查看。 当然这不是最好的解决方案,但速度很快。 在我的应用程序中,客户端设备以预定义方式(如“yesIamInTheterModeIamYourServer”)检查(向此地址发送数据包)和我的服务器设备响应。
链接地址: http://www.djcxy.com/p/72099.html