title: Android 10+ (API 29+) connect to Wi-fi in background programmatically
body: <p>In my Flutter app, I'm using native Android code (in Kotlin) to connect to a specific Wi-Fi programmatically. For Android 10+, I need to use network specifier. It works, <strong>but only if an app is in foreground</strong>. In background, I always end up in <code>onUnavailable</code> callback.</p>
  <p>In my specific use case, the app connects to a highly unstable Wi-Fi (it turns off and on all time). I need the app to be able to reconnect without any user interaction even with the display turned off.</p>
  <p>Is there a way to connect to a specific network in background?</p>
  <pre><code>val specifier = WifiNetworkSpecifier.Builder()
                  .setSsid(ssid)
                  .setBssid(MacAddress.fromString(macAddressString))
                  .apply {
                    if (isWpa3 != null &amp;&amp; isWpa3) {
                      setWpa3Passphrase(password)
                    } else {
                      setWpa2Passphrase(password)
                    }
                  }
                  .build()
  
  var request = NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                .setNetworkSpecifier(specifier)
                .build()
  
  
  this.networkCallback = object : ConnectivityManager.NetworkCallback() {
  
        override fun onAvailable(network: Network) {
          super.onAvailable(network)
          connectivityManager.bindProcessToNetwork(network)
         
          // Success
        }
  
        override fun onUnavailable() {
          super.onUnavailable()
  
          // Unavailable
          
          // Always end up here with display off
        }
  
      }
      // Defined elsewhere
      connectivityManager.requestNetwork(request, networkCallback)
  </code></pre>