oli*_*ra1 8 android udp broadcast wifi
我正在开发一个应用程序,它使用wifi在所有与我的应用程序在同一网络中的手机之间广播UDP消息.
我设法从许多具有外部AP的手机发送/接收数据包,这是我的路由器.
但鉴于没有AP的情况,我希望用户能够使用他们手机的Wifi热点功能,这样他们仍然可以使用我的应用程序.因此,其中一部手机将是wifi热点,其他所有手机都将连接到该热点.
我要求用户通过自己的方式连接到wifi.无论是外部AP还是外部AP.然后当我的应用程序启动时,它会检查手机是否连接到wifi网络,调用WifiManager.isWifiEnabled()和NetworkInfo.isConnected().
问题是,如果我在使用热点的手机中调用这些功能,则函数isConnected()将返回false.我无法使用WifiManager.getDhcpInfo()获取广播地址.连接到热点的其他手机完全可以正常工作.但由于WifiManager被禁用,热点手机无法发送任何广播.
所以,我的问题是"有没有办法检查手机目前是否是一个wifi热点?如果有的话,有什么办法可以获得它的广播地址吗?"
MP2*_*P23 13
首先,您可以检查您的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;
}
Run Code Online (Sandbox Code Playgroud)
我用这个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;
}
Run Code Online (Sandbox Code Playgroud)
它当然可以在一个方法中完成,但在我的实现中将它分成两个方法是有用的.
要确定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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果客户端设备需要知道服务器设备是否是移动热点,则可以使用特定的IP地址.据我所知,所有Tethering设备都具有相同的地址192.168.43.1在Android 2.3和4. +上是相同的,在许多手机和平板电脑上都有.当然,这不是最佳解决方案,但速度很快.在我的应用程序中,客户端设备检查(将数据包发送到此地址)和我的服务器设备以预定义的方式响应,如"yesIamInTheterModeIamYourServer".
| 归档时间: |
|
| 查看次数: |
8428 次 |
| 最近记录: |