Scan WiFi Network and Connect Example Android

Scan WiFi Network and Connect Example Android

In the last tutorial of WiFi network, we have learned about how to get available wifi networks and display them in a list in android. Here, In this part of the tutorial, we will learn about how to connect to specific SSID when the user selects the available wifi networks. In this article, we have to use code from the earlier article about how to get available wifi networks and list as the base app. So if you don’t go through the last tutorial you can check out it Scan and List all WiFi In Android.

Overview of the Project

First of all, we would like to give you the basic idea about the project work that we need to do to accomplish this Demo App.

  • Setup the click even on WiFi View from Adapter
  • Set the OnClickListener to adapter
  • Show Popup to user for Password Input of the Network
  • Get the type of security used by the Network
  • Connect to selected WiFi Network

Setup the click even on WiFi View from Adapter

So for adding the adding the click event to our WiFi view, we need to modify our WiFiScanAdpater and WiFi Fragment.

Declare the variable in WiFiScanAdapater class as given below

private View.OnClickListener mOnClickListener;

Then create a public method in same adapter class as given below

public void setOnClickListener(View.OnClickListener lis) {
        mOnClickListener = lis;
    }

Last change of WiFi Adapter class is to set the listener to the view. So inside of onCreateViewHolder method adapter add the below code.

itemView.setOnClickListener(mOnClickListener);

One more change we required in the adapter class to set the tag for the textView, that we use to show the name of the WiFi network. We will use this tag to identify the selected view in our WiFi Fragment class to connect that network. So add the below code to onBindViewHolder method of Adapter.

((MyViewHolder) holder).vName.setTag(device);

So what we have done using the above changes to our WiFi adapter class? We have created a method using which we can set the on click listener from our fragment by just calling the method like adapter.setOnClickListener.

Set the OnClickListener to WiFi Network adapter

For setting the Listener on the adapter of WiFi use the below code.

wifiScanAdapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
   }
        });

Show Popup to user to enter the password of WiFi Network

Next steps are to ask for the password when user tab on the network to get connected to WiFi SSID. For creating the custom Popup dialogue we need to create a layout XML file also. So create the menuwifi.xml file as given below.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:id="@+id/textViewSSID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SSID"
        tools:layout_editor_absoluteX="35dp"
        tools:layout_editor_absoluteY="0dp" />


    <TextView
        android:id="@+id/textViewSecurity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        />

    <TextView
        android:id="@+id/textViewPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Password"
        />

    <EditText
        android:id="@+id/editTextPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"

      />


</LinearLayout>
</android.support.constraint.ConstraintLayout>

Next, we need to modify the onClickListener method as given below for our WiFi adapter class.

wifiScanAdapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final device d=(device)v.findViewById(R.id.ssid_name).getTag();
                Log.d(TAG,"Selected Network is "+d.getName());

                LayoutInflater li = LayoutInflater.from(getContext());
                View promptsView = li.inflate(R.layout.menuwifi, null);
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        getContext());
                alertDialogBuilder.setView(promptsView);
                final EditText userInput = (EditText) promptsView
                        .findViewById(R.id.editTextPassword);
                TextView ssidText=(TextView)promptsView.findViewById(R.id.textViewSSID);
                ssidText.setText("Connecting to "+ d.getName());
                TextView security=(TextView)promptsView.findViewById(R.id.textViewSecurity);
                security.setText("Security for Network is:\n" +d.getCapabilities());
                alertDialogBuilder
                        .setCancelable(false)
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,int id) {
                                        // get user input from user for password
                                        Log.d(TAG,"Password is:" + userInput.getText());
                                        password=userInput.getText().toString();
                                      //Call the connectWiFi method to get connected the network
                                        connectWiFi(String.valueOf(d.getName()),password,d.capabilities);

                                    }
                                })
                        .setNegativeButton("Cancel",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,int id) {
                                        dialog.cancel();
                                    }
                                });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();

            }
        });

In the above code, we have used a method connectWiFi that we will create later on in this tutorial, this method take the required parameter and connect to the wifi network when user tab on ok button.

<

p class=”line-numbers”>connectWiFi(String.valueOf(d.getName()),password,d.capabilities);

Get the type of security used by the WiFi Network

Security of the WiFi network is important for us for making the connection to that network. Because on the basis of security type used by network we will choose the method to connect to the network.

So to get the security type of the network we have done some little modification in our device POJO class as given below. In which we have added the capabilities variable to get and store the security type used by the network. Modify the device class as given below.

public class device{
        CharSequence name;

        public String getCapabilities() {
            return capabilities;
        }

        public void setCapabilities(String capabilities) {
            this.capabilities = capabilities;
        }

        String capabilities;

        public void setName(CharSequence name) {
            this.name = name;
        }

        public CharSequence getName (){
            return name;
        }
    }

Using the below code we are getting the security type of the network and storing in device POJO.

d.setCapabilities(wifiList.get(netCount).capabilities);

Capabilities are returned by the scan results methods so using above code we are storing the capabilities in our wifiList List along with there SSID.

Create method to connect the selected WiFi Network

As we have to get the SSID, Security type as capabilities and password from the user.  So we are all set to create our connectWiFi method. Create and modify the connectWiFi method as given below.

public void connectWiFi(String SSID,String password,String Security) {
        try {

            Log.d(TAG, "Item clicked, SSID " + SSID + " Security : " + Security);

            String networkSSID = SSID;
            String networkPass = password;

            WifiConfiguration conf = new WifiConfiguration();
            conf.SSID = "\"" + networkSSID + "\"";   // Please note the quotes. String should contain ssid in quotes
            conf.status = WifiConfiguration.Status.ENABLED;
            conf.priority = 40;
// Check if security type is WEP
            if (Security.toUpperCase().contains("WEP")) {
                Log.v("rht", "Configuring WEP");
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
                conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);

                if (networkPass.matches("^[0-9a-fA-F]+$")) {
                    conf.wepKeys[0] = networkPass;
                } else {
                    conf.wepKeys[0] = "\"".concat(networkPass).concat("\"");
                }

                conf.wepTxKeyIndex = 0;
// Check if security type is WPA
            } else if (Security.toUpperCase().contains("WPA")) {
                Log.v(TAG, "Configuring WPA");

                conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);

                conf.preSharedKey = "\"" + networkPass + "\"";
// Check if network is open network
            } else {
                Log.v(TAG, "Configuring OPEN network");
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                conf.allowedAuthAlgorithms.clear();
                conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            }
//Connect to the network
            WifiManager wifiManager = (WifiManager) getActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            int networkId = wifiManager.addNetwork(conf);

            Log.v(TAG, "Add result " + networkId);

            List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
            for (WifiConfiguration i : list) {
                if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
                    Log.v(TAG, "WifiConfiguration SSID " + i.SSID);

                    boolean isDisconnected = wifiManager.disconnect();
                    Log.v(TAG, "isDisconnected : " + isDisconnected);

                    boolean isEnabled = wifiManager.enableNetwork(i.networkId, true);
                    Log.v(TAG, "isEnabled : " + isEnabled);

                    boolean isReconnected = wifiManager.reconnect();
                    Log.v(TAG, "isReconnected : " + isReconnected);

                    break;
                }
            }

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

Now we are all set to test our app, now you can run and test the app.

List WiFi Network

Connect to WiFi Network

 

 

 

 

 

 

 

 

MainActivity.java

package com.nplix.wifidemoapp;


import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
private FragmentManager fm;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        WifiFragment wifiFragment=WifiFragment.newInstance();
        ft.replace(R.id.main_container,wifiFragment);
        ft.commit();

    }
}

Full code of WifiFragment.java

package com.nplix.wifidemoapp;


import android.Manifest;
import android.bluetooth.BluetoothClass;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WifiFragment extends Fragment {
    public class device{
        CharSequence name;

        public String getCapabilities() {
            return capabilities;
        }

        public void setCapabilities(String capabilities) {
            this.capabilities = capabilities;
        }

        String capabilities;

        public void setName(CharSequence name) {
            this.name = name;
        }

        public CharSequence getName (){
            return name;
        }
    }
    final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 125;
    List<ScanResult> wifiList;
    private WifiManager wifi;
    List<device> values = new ArrayList<device>();
    int netCount=0;
    RecyclerView recyclerView;
    WifiScanAdapter wifiScanAdapter;
    private static String TAG="WifiFragment";
    private String password=null;
    //Option Menu for wifi connection



    public WifiFragment() {
        // Required empty public constructor
    }
    public static WifiFragment newInstance() {
        WifiFragment fragment = new WifiFragment();
        return fragment;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //Make instance of Wifi
        Button btnScan= (Button) getActivity().findViewById(R.id.wifiScan);
        wifi = (WifiManager) getActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        //Check wifi enabled or not
        if (wifi.isWifiEnabled() == false)
        {
            Toast.makeText(getActivity(), "Wifi is disabled enabling...", Toast.LENGTH_LONG).show();
            wifi.setWifiEnabled(true);
        }
        //register Broadcast receiver
        getActivity().registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                wifiList=wifi.getScanResults();
                netCount=wifiList.size();
               // wifiScanAdapter.notifyDataSetChanged();
                Log.d("Wifi","Total Wifi Network"+netCount);
            }
        },new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
       wifiScanAdapter=new WifiScanAdapter(values,getContext());
       recyclerView= (RecyclerView) getActivity().findViewById(R.id.wifiRecyclerView);
       recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(wifiScanAdapter);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkandAskPermission();
        } else {
            wifi.startScan();
            values.clear();
            try {
                netCount = netCount - 1;
                while (netCount >= 0) {
                    device d = new device();
                    d.setName(wifiList.get(netCount).SSID.toString());
                    d.setCapabilities(wifiList.get(netCount).capabilities);
                    Log.d("WiFi",d.getName().toString());
                    values.add(d);
                    wifiScanAdapter.notifyDataSetChanged();
                    netCount=netCount -1;
                }
            }
            catch (Exception e){
                Log.d("Wifi", e.getMessage());
            }
        }
       btnScan.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {

               wifi.startScan();
               values.clear();
               try {
                   netCount=netCount -1;
                   while (netCount>=0){
                       device d= new device();
                       d.setName(wifiList.get(netCount).SSID.toString());
                       d.setCapabilities(wifiList.get(netCount).capabilities);
                       values.add(d);
                       wifiScanAdapter.notifyDataSetChanged();
                       netCount=netCount -1;
                   }
               }
               catch (Exception e){
                   Log.d("Wifi", e.getMessage());
               }
           }
       });
        wifiScanAdapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final device d=(device)v.findViewById(R.id.ssid_name).getTag();
                Log.d(TAG,"Selected Network is "+d.getName());

                LayoutInflater li = LayoutInflater.from(getContext());
                View promptsView = li.inflate(R.layout.menuwifi, null);
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        getContext());
                alertDialogBuilder.setView(promptsView);
                final EditText userInput = (EditText) promptsView
                        .findViewById(R.id.editTextPassword);
                TextView ssidText=(TextView)promptsView.findViewById(R.id.textViewSSID);
                ssidText.setText("Connecting to "+ d.getName());
                TextView security=(TextView)promptsView.findViewById(R.id.textViewSecurity);
                security.setText("Security for Network is:\n" +d.getCapabilities());
                alertDialogBuilder
                        .setCancelable(false)
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,int id) {
                                        // get user input from user for password
                                        Log.d(TAG,"Password is:" + userInput.getText());
                                        password=userInput.getText().toString();
                                      //Call the connectWiFi method to get connected the network
                                        connectWiFi(String.valueOf(d.getName()),password,d.capabilities);

                                    }
                                })
                        .setNegativeButton("Cancel",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,int id) {
                                        dialog.cancel();
                                    }
                                });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();

            }
        });
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        return inflater.inflate(R.layout.fragment_wifi, container, false);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
                Map<String, Integer> perms = new HashMap<String, Integer>();
                perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED);
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                if (perms.get(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    wifi.startScan();
                } else {
                    // Permission Denied
                    Toast.makeText(getContext(), "Some Permission is Denied", Toast.LENGTH_SHORT)
                            .show();
                }
            }
        }
    }

    private void checkandAskPermission() {
        List<String> permissionsNeeded = new ArrayList<String>();

        final List<String> permissionsList = new ArrayList<String>();
        if (!addPermission(permissionsList, Manifest.permission.ACCESS_COARSE_LOCATION))
            permissionsNeeded.add("Network");


        if (permissionsList.size() > 0) {
            if (permissionsNeeded.size() > 0) {
                // Need Rationale
                String message = "You need to grant access to " + permissionsNeeded.get(0);
                for (int i = 0; i < permissionsNeeded.size(); i++)
                    message = message + ", " + permissionsNeeded.get(i);
                showMessageOKCancel(message,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                                        REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
                            }
                        });
                return;
            }

            requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                    REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
            return;
        }
       // initVideo();
    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(getActivity())
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", okListener)
                .create()
                .show();
    }

    private boolean addPermission(List<String> permissionsList, String permission) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (getActivity().checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                permissionsList.add(permission);
                if (!shouldShowRequestPermissionRationale(permission))
                    return false;
            }
        }
        return true;
    }

        public void connectWiFi(String SSID,String password,String Security) {
            try {

                Log.d(TAG, "Item clicked, SSID " + SSID + " Security : " + Security);

                String networkSSID = SSID;
                String networkPass = password;

                WifiConfiguration conf = new WifiConfiguration();
                conf.SSID = "\"" + networkSSID + "\"";   // Please note the quotes. String should contain ssid in quotes
                conf.status = WifiConfiguration.Status.ENABLED;
                conf.priority = 40;

                if (Security.toUpperCase().contains("WEP")) {
                    Log.v("rht", "Configuring WEP");
                    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                    conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                    conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                    conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                    conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
                    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);

                    if (networkPass.matches("^[0-9a-fA-F]+$")) {
                        conf.wepKeys[0] = networkPass;
                    } else {
                        conf.wepKeys[0] = "\"".concat(networkPass).concat("\"");
                    }

                    conf.wepTxKeyIndex = 0;

                } else if (Security.toUpperCase().contains("WPA")) {
                    Log.v(TAG, "Configuring WPA");

                    conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                    conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
                    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);

                    conf.preSharedKey = "\"" + networkPass + "\"";

                } else {
                    Log.v(TAG, "Configuring OPEN network");
                    conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                    conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                    conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                    conf.allowedAuthAlgorithms.clear();
                    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                    conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
                    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                    conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                }

                WifiManager wifiManager = (WifiManager) getActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                int networkId = wifiManager.addNetwork(conf);

                Log.v(TAG, "Add result " + networkId);

                List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
                for (WifiConfiguration i : list) {
                    if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
                        Log.v(TAG, "WifiConfiguration SSID " + i.SSID);

                        boolean isDisconnected = wifiManager.disconnect();
                        Log.v(TAG, "isDisconnected : " + isDisconnected);

                        boolean isEnabled = wifiManager.enableNetwork(i.networkId, true);
                        Log.v(TAG, "isEnabled : " + isEnabled);

                        boolean isReconnected = wifiManager.reconnect();
                        Log.v(TAG, "isReconnected : " + isReconnected);

                        break;
                    }
                }

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

WifiScanAdapter.java

package com.nplix.wifidemoapp;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;


public class WifiScanAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private List<WifiFragment.device> wifiList;
private Context context;
private View.OnClickListener mOnClickListener;

    public WifiScanAdapter(List<WifiFragment.device> wifiList, Context context) {
        this.wifiList = wifiList;
        this.context=context;

    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {

            View itemView = LayoutInflater.
                    from(viewGroup.getContext()).
                    inflate(R.layout.network_list, viewGroup, false);

         MyViewHolder holder = new MyViewHolder(itemView);
            itemView.setTag(holder);
            itemView.setOnClickListener(mOnClickListener);
            return holder;

    }
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {


           WifiFragment.device device=wifiList.get(position);
           String name=device.getName().toString();

             ((MyViewHolder) holder).vName.setText(name);
             ((MyViewHolder) holder).vName.setTag(device);


            ((MyViewHolder) holder).vImage.setImageResource(R.drawable.ic_action_wifi);
            ((MyViewHolder) holder).context = context;
            ((MyViewHolder) holder).position = position;
    }
    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }


    @Override
    public int getItemCount() {

        int itemCount = wifiList.size();

        return itemCount;
    }
    public void setOnClickListener(View.OnClickListener lis) {
        mOnClickListener = lis;
    }
    public class MyViewHolder extends RecyclerView.ViewHolder {
        protected ImageView vImage;
        protected TextView vName;
        protected  Context context;
        protected int position;


        public MyViewHolder(View v) {
            super(v);
            vName = v.findViewById(R.id.ssid_name);
            vImage = v.findViewById(R.id.Wifilogo);

        }
    }

}

Conclusion

As you can see that writing the code to list and connect to the network is not so hard, it is quite a simple one. We have just created a Fragment and Adapter Class and set the Fragment form, main class. You can also download the source code from https://github.com/debugandroid/WiFiDemoApp.

If you have any question or query on same then you can write below in comment section.

Get Email Updates!

Signup now receive an email once I publish new content. I will never give away, trade or sell your email address. You can unsubscribe at any time.

Join 911 other subscribers

This Post Has One Comment

Leave a Reply

Close Menu