问题描述
我正在开发一种用户必须遵循以下步骤的应用程序:
I am working on an application in which one the user has to follow these steps :
- 将手机连接到wifi
- 将电话从连接的对象连接到专用热点.
当用户连接到连接对象的专用热点时,应用程序会执行一些HTTP请求以对其进行配置.然后,我想自动将应用程序重新连接到步骤1的全局wifi.
When the user is connected to the dedicated hotspot of the connected object, the application does some HTTP requests in order to configure it. Then, I would like to reconnect automatically the application to the global wifi of the step 1.
从API 21到API 28,此功能非常易于实现,因为我知道要将手机重新连接到的SSID.只需几行代码即可完成:
From API 21 to API 28 this feature is very easy to implement because I know the SSID I want to reconnect the phone to. It can be done with few line of code:
private fun changeCurrentWifiNetworkLegacy(ssidToConnect: String) {
val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
var ssidIdentifier: Int? = null
wifiManager.configuredNetworks?.forEach { config ->
Log.d("SSID", config.SSID)
if (config.SSID == "\"${ssidToConnect}\"") {
ssidIdentifier = config.networkId
}
}
ssidIdentifier?.let { id ->
wifiManager.enableNetwork(id, true)
}
}
在API 29上,根据本文,此简单代码不再起作用: https://developer.android.com/about/versions/10/privacy/changes#configure-wifi
On API 29 this simple code does not work anymore according to this article : https://developer.android.com/about/versions/10/privacy/changes#configure-wifi
根据这篇文章,现在,我应该使用2个类:WifiNetworkSpecifier
和/或WifiNetworkSuggestion
.
According to the article, now, I should use 2 classes : WifiNetworkSpecifier
and/or WifiNetworkSuggestion
.
不幸的是,我找不到使用这些类的有效示例,以将用户连接到先前配置的SSID.
Unfortunately, I cannot find a working example using these classes in order to connect the user to a previous configured SSID.
有人已经实现了吗?
预先感谢您的帮助.
推荐答案
只要万一有可怜的人遇到这种情况,API很有可能在您的设备上就被破坏了.在我的OnePlus 5,Android 10,Build 200513上,会发生以下情况:
Just in case any poor soul encounters this, it's completely possible the API is just broken on your device. On my OnePlus 5, Android 10, Build 200513, this happens:
- 呼叫requestNetwork.我是否使用Listener或PendingIntent版本都没关系
- 操作系统找到网络,进行连接,onAvailable,并称为朋友
- 操作系统立即断开连接.我可以在logcat中看到应用已释放请求,正在取消NetworkRequest"
- 但是,这不是真的-并未取消该请求,Android重新关联了该请求,并重新开始了连接到网络的过程.转到2.并重复一遍.
为此创建了一个Android错误: https://issuetracker.google.com/issues/158344328
Created an Android bug for this: https://issuetracker.google.com/issues/158344328
此外,如果您不以正确的顺序终止应用程序和对话框,并且仅重新启动,则可以使操作系统进入不再显示要与之配合使用的设备"对话框的状态.
Additionally, you can get the OS into state when it will no longer show the "Device to use with " dialog if you don't terminate your app and the dialogs in the correct order, and only reboot helps.
只需为自己省事,以Android 9为目标,然后使用WifiManager API(如果以10为目标,则很有用).与新的requestNetwork API相比,它甚至具有更好的用户体验.
Just save yourself the trouble, target Android 9 and use the WifiManager APIs (that are helpfully broken if you target 10). It even has better user experience than the new requestNetwork APIs.
这篇关于Android 10/API 29:如何将手机连接到已配置的网络?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!