无法使用 ConnectivityManager 连接到 wifi
我正在尝试使用代码连接到 wifi。这是我的简化代码:
val wifiNetworkSpecifier = WifiNetworkSpecifier.Builder()
.setSsid(ssid)
.setWpa2Passphrase(password)
.build()
val networkRequest = NetworkRequest.Builder().apply {
addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
if (useCapabilities) {
addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
}
setNetworkSpecifier(wifiNetworkSpecifier)
}.build()
connectivityManager.requestNetwork(networkRequest, networkCallback)
完整代码可以可以在这里找到
当 useCapability 为 true 时,我没有得到任何视觉反馈,回调也没有帮助。当我设置功能时 onUnavailable()
被调用,但我看不出原因。我可以连接到我手动尝试的同一网络。
我这里有一个完整的示例应用程序: https://github.com/rekire/WifiBug
请告诉我我做错了什么。我使用的是运行 Android 12 的 Pixel 6。
I'm trying to connect to a wifi with code. Here is my simplified code:
val wifiNetworkSpecifier = WifiNetworkSpecifier.Builder()
.setSsid(ssid)
.setWpa2Passphrase(password)
.build()
val networkRequest = NetworkRequest.Builder().apply {
addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
if (useCapabilities) {
addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
}
setNetworkSpecifier(wifiNetworkSpecifier)
}.build()
connectivityManager.requestNetwork(networkRequest, networkCallback)
The full code can be found here
When useCapabilities
is true I get no visual feedback, the callbacks are not helpful too. When I set the capabilities onUnavailable()
is called, but I see no reason why. I can connect with the same network which I try it by hand.
I have a full sample app here: https://github.com/rekire/WifiBug
Please tell me what I'm doing wrong. I'm using a Pixel 6 with Android 12.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
WifiNetworkSpecifier 不适合与
NET_CAPABILITY_INTERNET
功能一起使用,因此它始终会调用onUnavailable
。我在这里解释我的自我回答问题: https://stackoverflow.com/a/73178258/467509我个人认为Google 应该在 Android Studio 中以 linter 或其他方式告诉您这一点,而不仅仅是调用
onUnavailable
并将调试消息隐藏在 LogCat 中。WifiNetworkSpecifier is not meant to work with capability
NET_CAPABILITY_INTERNET
so it will always callonUnavailable
. I explain in my self-answered question here: https://stackoverflow.com/a/73178258/467509I personally think Google should tell you this in Android Studio in a linter or something, and not just call
onUnavailable
and bury a debug message in LogCat.