从 ConnectivityManager NetworkCapability 同步获取 Wifi SSID
目前,获取 Android 设备连接的 Wifi 网络 SSID 最流行的方法是使用 WifiManager 的 getConnectionInfo() 方法。但是,该方法在 API 级别 31 中已被弃用。根据文档,我们预计使用 ConnectivityManager 的 getNetworkCapability() 方法来获取 Wifi 信息。不幸的是,文档指出
这将删除嵌入 NetworkCapability#getTransportInfo() 中的 TransportInfo 中的所有位置敏感数据。某些传输信息实例(例如 WifiInfo)包含位置敏感信息。系统将记录检索此位置敏感信息(取决于应用程序的位置权限)。要在 TransportInfo 中包含任何位置敏感数据,请使用带有 NetworkCallback#FLAG_INCLUDE_LOCATION_INFO 标志的 NetworkCallback。
现在获取 SSID 的唯一方法似乎是使用 FLAG_INCLUDE_LOCATION_INFO 标志注册 NetworkCallback 并等待回调被调用。这不是旧方法的合适替代品,因为旧方法是同步的并且可以按需调用。目前是否有任何方法可以同步获取 Wifi SSID,而不使用已弃用的 getConnectionInfo() 方法?
Currently, the most popular method of getting the SSID of the Wifi network the Android device is connected to is using WifiManager's getConnectionInfo() method. However, that method is deprecated in API level 31. According to the documentation, we're expected to use ConnectivityManager's getNetworkCapabilities() method to get the Wifi info. Unfortunately, the documentation states
This will remove any location-sensitive data in TransportInfo embedded in NetworkCapabilities#getTransportInfo(). Some transport info instances like WifiInfo contain location-sensitive information. Retrieving this location-sensitive information (subject to the app's location permissions) will be noted by the system. To include any location-sensitive data in TransportInfo, use a NetworkCallback with NetworkCallback#FLAG_INCLUDE_LOCATION_INFO flag.
It seems like the only way now to get the SSID is by registering a NetworkCallback with the FLAG_INCLUDE_LOCATION_INFO flag and waiting until the callback is invoked. This is not a suitable replacement for the old method as the old method was synchronous and could be called on-demand. Is there currently any way to get the Wifi SSID synchronously without using the deprecated getConnectionInfo() method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我也有这个问题。需要同步查询吗?您能否将
onCapabilitiesChanged()
的最后一个 SSID 输出存储在 livedata 对象中,这是一个非常好的资源,可以帮助您做到这一点。不幸的是,我的代码仍然给我使用传输信息的 SSID 信息为空。你能分享你的代码吗?I am having issues with this also. Do you need to query this synchronously? Can you not just store the last SSID output from
onCapabilitiesChanged()
in a livedata object, this is a really nice resource to help you do that. Unfortunately my code is still giving me null for SSID information using transport info. Can you share your code?试试下面的例子,在Thread中调用方法
getWiFiSSID()
Try the example below, call the method
getWiFiSSID()
inside Thread"" 避免这种情况的唯一方法是在设备上启用 GPS,也就是说,除了获得所有必要的权限之外,还必须在请求时启用 GPS
"" the only way to avoid this is to enable GPS on the device, that is, apart from getting all the necessary permissions, GPS must be enabled at the time of the request