How to validate password of wifi and connect/disconnect specific wifi network in android 10

1.2k views Asked by At

I am trying to connect a specific wifi network in android 10 (API level 29). I have written a function for this is given below,

    private void connectToWifi(final String ssid, String password) {
    count=0;

    wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    if (!wifiManager.isWifiEnabled()){
        wifiManager.setWifiEnabled(true);
        System.out.println("Wifi is enabled");
    }

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        System.out.println("Android sdk version is 29 above");

        final WifiNetworkSuggestion suggestion1 =
                new WifiNetworkSuggestion.Builder()
                        .setSsid(ssid)
                        .setIsAppInteractionRequired(true) // Optional (Needs location permission)
                        .build();

        final WifiNetworkSuggestion suggestion2 =
                new WifiNetworkSuggestion.Builder()
                        .setSsid(ssid)
                        .setWpa2Passphrase(password)
                        .setIsAppInteractionRequired(true) // Optional (Needs location permission)
                        .build();

        final WifiNetworkSuggestion suggestion3 =
                new WifiNetworkSuggestion.Builder()
                        .setSsid(ssid)
                        .setWpa3Passphrase(password)
                        .setIsAppInteractionRequired(true) // Optional (Needs location permission)
                        .build();

        final List<WifiNetworkSuggestion> suggestionsList =
                new ArrayList<WifiNetworkSuggestion>();
        suggestionsList.add(suggestion1);
        suggestionsList.add(suggestion2);
        suggestionsList.add(suggestion3);


        WifiNetworkSpecifier.Builder builder = new WifiNetworkSpecifier.Builder();
        builder.setSsid(ssid);
        builder.setWpa2Passphrase(password);

        final int status = wifiManager.addNetworkSuggestions(suggestionsList);
        if (status != WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS) {
            System.out.println("Status:" +status);
            // do error handling hereā€¦
        }

        WifiNetworkSpecifier wifiNetworkSpecifier = builder.build();

        NetworkRequest.Builder networkRequestBuilder1 = new NetworkRequest.Builder();
        networkRequestBuilder1.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
        networkRequestBuilder1.setNetworkSpecifier(wifiNetworkSpecifier);

        NetworkRequest nr = networkRequestBuilder1.build();
        final ConnectivityManager cm = (ConnectivityManager)
                getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        final ConnectivityManager.NetworkCallback networkCallback = new
                ConnectivityManager.NetworkCallback() {
                    @Override
                    public void onAvailable(Network network) {
                        super.onAvailable(network);
                        Log.d("MainActivity", "onAvailable:" + network);
                        cm.bindProcessToNetwork(network);
                    }

                    @Override
                    public void onLosing(@NonNull Network network, int maxMsToLive) {
                        super.onLosing(network, maxMsToLive);
                        System.out.println("onLosing" + network);
                    }

                    @Override
                    public void onLost(@NonNull Network network) {
                        super.onLost(network);
                        System.out.println("onLost" + network);
                    }

                    @Override
                    public void onUnavailable() {
                        super.onUnavailable();
                        System.out.println("onUnavaliable");
                        Toast.makeText(MainActivity.this, "Your Password is incorrect", Toast.LENGTH_SHORT).show();
                    }
                };
        cm.requestNetwork(nr, networkCallback);

        final IntentFilter intentFilter = new IntentFilter(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION);

        final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override public void onReceive(Context context, Intent intent) {
                if (!intent.getAction().equals(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION)) {
                    System.out.println("ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION Failed");
                    return;
                }else {
                    System.out.println("Connection Successful..........");
                }
                // Post connection
            }
        };
        getApplicationContext().registerReceiver(broadcastReceiver, intentFilter);

    }  else{
        try {
            WifiConfiguration wifiConfig = new WifiConfiguration();
            wifiConfig.SSID = "\"" + ssid + "\"";
            wifiConfig.preSharedKey = "\"" + password + "\"";
            int  netId = wifiManager.addNetwork(wifiConfig);
            wifiManager.disconnect();
            wifiManager.enableNetwork(netId, true);
            wifiManager.reconnect();

            IntentFilter wifiStatusIntentFilter = new IntentFilter();
            wifiStatusIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
            wifiStatusIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
            //wifiStatusIntentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);


                       final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
                           @Override public void onReceive(Context context, Intent intent) {
                               String action = intent.getAction();


                               if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {

                                   NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

                                   WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                                   String str = wifiInfo.getSSID().replace("\"", "");
                                   switch (info.getState())
                                   {

                                       case CONNECTING:
                                           System.out.println("Connecting");
                                           System.out.print("\nWifiInfo: " +str);
                                           System.out.print("\nUserInput SSID: " +ssid);

                                           break;

                                       case CONNECTED:
                                           if(str.equals(ssid)) {
                                               System.out.println("Connected ... str.equals(ssid) " + count);
                                               System.out.println("Connected" );
                                               passwordIsCoorectError="correct";
                                               returnWifConnection("1234", "correct");
                                            //   return "correct";
                                           }

                                           //count = 1;
                                           break;
                                       case DISCONNECTING:
                                           System.out.println("Disconnecting");
                                           break;
                                       case DISCONNECTED:
                                           System.out.println("Disconnected");
                                           System.out.println("Disconnected->str" +str);
                                           System.out.println("Disconnected->ssid" +ssid);
                                           count ++;
                                           if(str.equals(ssid))
                                           {
                                               System.out.println("count str.equals(ssid) "+count);
                                           //   count = 1;
                                           if(count==5)
                                           {
                                               System.out.println("count===5 "+count);
                                            //   Toast.makeText(MainActivity.this, "Your Password is incorrect", Toast.LENGTH_SHORT).show();
                                         passwordIsCoorectError="wrong";
                                         returnWifConnection("1234", "wrong");
                                              // return "wrong";

                                               }

                                           }

                                           break;
                                       case SUSPENDED:
                                           System.out.println("Suspended");
                                           break;
                                   }
                               }
                           }
                       };


            getApplicationContext().registerReceiver(broadcastReceiver, wifiStatusIntentFilter);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

My code does not give me a proper result for this validation. Actually, I have issues when I connect to wifi with the wrong password and try to connect again with right password with this code. Wifi does not connected, the control goes in always onUnavailable() method of NetworkCallback class. Please help me for finding a solution.

1

There are 1 answers

0
Aimkiller On
final NetworkSpecifier specifier =
                new WifiNetworkSpecifier.Builder()
                        .setSsidPattern(new PatternMatcher("wifissid", PatternMatcher.PATTERN_PREFIX))
                        .setWpa2Passphrase("wifipassword")
                        .build();
        final NetworkRequest request =
                new NetworkRequest.Builder()
                        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                        .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                        .setNetworkSpecifier(specifier)
                        .build();
        final ConnectivityManager connectivityManager =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        final ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(@NonNull Network network) {
                super.onAvailable(network);
                Toast.makeText(WControllerActivity.this, "Connected!", Toast.LENGTH_SHORT);
            }
        };
        connectivityManager.requestNetwork(request, networkCallback);

This works from Android Q

You need add permissions to your manifest.

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>