In my app, I'm trying to connect automatically to a specific SSID (in android Q). I'm using "WifiNetworkSpecifier","NetworkRequest" and "ConnectivityManager" classes to do that. When I do a request, then a dialog appears on screen asking me to connect to this SSID, I click and then it connects. But there are two problems:
It's not really connected (no internet), I have to disable and enable WiFi to have the chance to be really connected!
When I clear app from memory it is automatically disconnected.
I'm looking to resolve these problems, but there is not enough example or sample. This is what I do in my source code:
fun connectToWifi(networkSSID: String, networkPassword: String?, bssid: String?)
val specifier = WifiNetworkSpecifier.Builder()
.setSsid(networkSSID)
if (networkPassword != null) {
specifier.setWpa2Passphrase(networkPassword)
}
if (bssid != null) {
specifier.setBssid(MacAddress.fromString(bssid))
}
val request = NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.setNetworkSpecifier(specifier.build())
.build()
val connectivityManager =
singletonArgument.context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network?) {
Log.d(TAG, "network available")
}
override fun onUnavailable() {
Log.d(TAG, "network unavailable")
}
}
connectivityManager.requestNetwork(request, networkCallback)
}