Best solution I found at the moment:
令我感到困惑的是,关于网络共享的信息/界面是如此繁琐/隐藏得到,但是当你从 WifiManager 或 ConnectivityManager 获取Wifi类型的信息时却没有考虑到:它只在不在网络共享时起作用 . 我实际上已经失去了那个调查分支 .
我目前发现的最佳解决方案是使用标准Java NetworkInterface.getNetworkInterfaces() ,而不是任何Android API .
Experimentally, Android seems smart enough to set to null broadcast for network interfaces to the external mobile network . 它实际上很有意义,因为Android默默地丢弃涉及外部移动网络的UDP广播 .
// This works both in tethering and when connected to an Access Point
Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements())
{
NetworkInterface networkInterface = interfaces.nextElement();
if (networkInterface.isLoopback())
continue; // Don't want to broadcast to the loopback interface
for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses())
{
InetAddress broadcast = interfaceAddress.getBroadcast();
// InetAddress ip = interfaceAddress.getAddress();
// interfaceAddress.getNetworkPrefixLength() is another way to express subnet mask
// Android seems smart enough to set to null broadcast to
// the external mobile network. It makes sense since Android
// silently drop UDP broadcasts involving external mobile network.
if (broadcast == null)
continue;
... // Use the broadcast
}
}
对于子网掩码, getNetworkPrefixLength() 的结果可以强制转换为子网掩码 . 我直接使用了 getBroadcast() ,因为这是我的最终目标 .
此代码似乎不需要特殊权限(没有 ACCESS_WIFI_STATE 也没有 NETWORK ,只有 INTERNET ) .