0

I managed to connect to wifi programmatically using the code bellow, but it's always prompting the user to "manually" connect to the wifi. I there a way to avoid this and automatically connect to the wifi ?

        NetworkCallback networkCallback = new NetworkCallback(){
        @Override
        public void onAvailable(Network network) {
            super.onAvailable(network);
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                connectivityManager.bindProcessToNetwork(network);
            }else{
                connectivityManager.setProcessDefaultNetwork(network);
            }
        }

        @Override
        public void onLost(Network network) {
            super.onLost(network);
            connectivityManager.bindProcessToNetwork(null);
            connectivityManager.unregisterNetworkCallback(this);
        }

    };

    WifiNetworkSpecifier networkSpecifier = new WifiNetworkSpecifier.Builder()
            .setSsid(SSID)
            .setWpa2Passphrase(Password)
            .build();

    NetworkRequest networkRequest = new NetworkRequest.Builder()
            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
            .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
            .addCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED)
            .setNetworkSpecifier(networkSpecifier)
            .build();

    connectivityManager.requestNetwork(networkRequest,networkCallback);

Popup asking user to connect to wifi

  • Does this answer your question? [How do I connect to a specific Wi-Fi network in Android programmatically?](https://stackoverflow.com/questions/8818290/how-do-i-connect-to-a-specific-wi-fi-network-in-android-programmatically) – DevWithZachary Dec 07 '21 at 14:35
  • Thank you for the link. But, this does answer my question, I used a similar thread to implement the wifi connection. I just want to avoid the popup asking the user to connect to the wifi. – Manuel DESTOUESSE Dec 08 '21 at 15:24
  • I added a link to the popup displayed on the screen, asking the user to connect to wifi. I would like to avoid this popup and and connect automatically. – Manuel DESTOUESSE Dec 08 '21 at 17:31
  • As far as I can tell, there is no way to what you want from the API 29 and above. The SDK now restricts all the network management from code and forces the user to choose the network he wants to connect. Also, the WifiNetworkSpecifier you used is used for creating a peer to peer connection for a specific work, it doesn't change the network for the OS. As soon as the work binded to the process ends, the connection ends. – aguiarroney Jul 07 '22 at 18:41
  • Take a look on this post https://stackoverflow.com/questions/56905956/is-it-possible-to-add-a-network-configuration-on-android-q – aguiarroney Jul 07 '22 at 18:43

0 Answers0