I'm using the new API 29 for connecting the device to a wifi network in an Android 10 device:
private val connectivityManager: ConnectivityManager by inject()
override fun connectToNetwork(ssid: String, password: String) {
val networkRequest = buildNetworkRequest(ssid, password)
val networkCallback =
object : NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
Timber.d("Connected to network $ssid")
}
override fun onUnavailable() {
super.onUnavailable()
Timber.e("Unable to connect to network $ssid")
}
}
connectivityManager.requestNetwork(networkRequest, networkCallback, CONNECTION_TIME_OUT)
}
private fun buildNetworkRequest(ssid: String, password: String) =
NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.setNetworkSpecifier(buildWifiNetworkSpecifier(ssid, password))
.build()
private fun buildWifiNetworkSpecifier(ssid: String, password: String) =
WifiNetworkSpecifier.Builder()
.setSsid(ssid)
.setWpa2Passphrase(password)
.build()
A dialog appears with a "Device to use with " with the specified wifi network listed. The dialog has two buttons for "cancel" and "connect". When I click "connect", the device connects to the wifi network (I can see that in the system settings) and the connect button is disabled.
But the dialog does not go away and none of the methods in the requestNetwork callback is invoked. Eventually I reach the specified timeout and another dialog comes with "Something came up. The application has cancelled the request to choose a device".
What is happening here? I want to connect to a network and have the 'onAvailable' or 'onUnavailable' methods in the callback invoked.