isuPatches / android-wisefy

Wrapper around WifiManager and ConnectivityManager for Android
Apache License 2.0
312 stars 38 forks source link

Connect with password #155

Closed fernando-s97 closed 1 year ago

fernando-s97 commented 3 years ago

How to connect to an SSID with password?

Are there any examples available? The current example app doesn't seem to have such an example

isuPatches commented 2 years ago

Hi there, I apologize for the late response here. To connect to a network, we only need the SSID to build the network connection request and/or get the network id for the connection. connectToNetwork has the implicit assumption that this network has already been added to the save network configurations.

interface NetworkConnectionApi {
    fun connectToNetwork(ssidToConnectTo: String, timeoutInMillis: Int): NetworkConnectionResult
    fun disconnectFromCurrentNetwork(): NetworkConnectionResult
}
interface NetworkConnectionApiAsync {
    fun connectToNetwork(ssidToConnectTo: String, timeoutInMillis: Int, callbacks: ConnectToNetworkCallbacks?)
    fun disconnectFromCurrentNetwork(callbacks: DisconnectFromCurrentNetworkCallbacks?)
}

Internally for Pre-SDK 29 devices, the library does this:

 when (val savedNetworkData = savedNetworkUtil.searchForSavedNetwork(ssidToConnectTo)) {
            null -> return NetworkConnectionResult.NetworkNotFound
            is SavedNetworkData.Configuration -> {
                savedNetworkData.data.let {
                    wifiManager.disconnect()
                    wifiManager.enableNetwork(it.networkId, true)
                    wifiManager.reconnect()
                    return NetworkConnectionResult.Succeeded(waitToConnectToSSID(ssidToConnectTo, timeoutInMillis))
                }
            }
        }

And for post-SDK 29 devices, the library does this:

        val networkRequest = NetworkRequest.Builder()
            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
            .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
            .setNetworkSpecifier(
                WifiNetworkSpecifier.Builder()
                    .setSsid(ssidToConnectTo)
                    .build()
            )
            .build()

        connectionManager.requestNetwork(networkRequest, networkCallback, timeoutInMillis)

I am going to keep this issue open until #145 is complete which will document this better.