Search code examples
androidwifi

Android connection to Wi-Fi seems not to have access to internet


I'm trying to connect to a WiFi network (WPA2 protected) using this code:

val mConnectivityManager =
   context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
val networkSpecifier = WifiNetworkSpecifier.Builder()
    .setSsid(SSID)
    .setWpa2Passphrase(key)
    .build()

val networkRequest = NetworkRequest.Builder()
   .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
   .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
   .addCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED)
   .setNetworkSpecifier(networkSpecifier)
   .build()

mConnectivityManager?.requestNetwork(
   networkRequest,
   object : ConnectivityManager.NetworkCallback() {

   })

It does work and it connects to the Wi-Fi network. However, sometimes the network doesn't access to internet for some weird reason. Connecting to the network normally using settings doesn't have this issue at all. Any idea why?


Solution

  • The issue for me seemed to be that this was missing:

    .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)