Search code examples
androidnetwork-programmingwifi

Connect to WIFI network from android application (Android 12+)


I'm trying to connect to wifi from my android application, using the wifi Network request API. Here is the code:

val builder =
 WifiNetworkSpecifier.Builder()         
 .setBssid(MacAddress.fromString(item.bssid))
 .setWpa2Passphrase("somePassword")
if (item.ssid.isNotEmpty()) {
    builder.setSsid(item.ssid)
  }
val networkRequest = NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.setNetworkSpecifier(builder.build())
.build()

Next I do that

cm.requestNetwork(
networkRequest,
WifiConnectionCallBack(ConnectivityManager)
)

WifiConnectionCallBack is my class, what extends NetworkCallback


class WifiConnectionCallBack(
    private val connectionWatcher : ConnectionWatcher,
    private val bssid : String,
    private val connManager: ConnectivityManager,
    private val onConnection : (Boolean, Network) -> Unit
) : NetworkCallback() {

    override fun onAvailable(network: Network) {
        super.onAvailable(network)
        val result = connManager.bindProcessToNetwork(network)
        onConnection.invoke(result, network)
        connectionWatcher.onChangeState(ConnectionState.WifiConnected(bssid, network))
    }

    override fun onUnavailable() {
        super.onUnavailable()
        connectionWatcher.onChangeState(ConnectionState.UnAvailable)
    }

    override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) {
        super.onLinkPropertiesChanged(network, linkProperties)
        connectionWatcher.onChangeState(
            ConnectionState.LinkPropertiesChanged(
                bssid,
                network,
                linkProperties
            )
        )
    }

    override fun onLost(network: Network) {
        super.onLost(network)
        connectionWatcher.onChangeState(ConnectionState.Lost(network))
    }

It works fine... But, when I HAVE NO access to the internet. Any suggestions, what can be wrong here? Thank you for reading this!

I tried methods from this topic Connect to Wifi in Android Q programmatically

But it doesnt work


Solution

  • This API is meant to connect to a local devices Network (peer-to-peer communication) for e.g. configuration purposes, NOT to connect to the internet.

    https://developer.android.com/guide/topics/connectivity/wifi-bootstrap

    If you want to connect to the internet consider using: https://developer.android.com/guide/topics/connectivity/wifi-suggest

    Though I'm not sure you can force the system to actually use the wifi you suggest.