Re: Connect to a wifi network programmatically

BumbleBee

I wish to create an application, that detects the available wifi connections in the vicinity, and then connects to them. What I have done till now, is that I created a ListView that lists the available wifi connections, and then I created a LongItemClick dialog box, that shows the SSID and the BSSID of the network, and asks for the password. Now, I wish to connect to one of the networks, independent of what kind of network it is, it might be WEP, WPA or Open too. I am unable to get an overview of how should I connect to them. Can anyone help me with this ? I searched all available answers, and I didn't find any answer, that could help me do this!

I try the above thing by the below method. I create a list view of all the available wi-fi networks in the vicinity, and then I try to show the connection info on long press, and give an option to connect to the clicked wi-fi network via click.

Code:

package com.example.random;



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

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.FragmentManager;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;    
import android.content.Intent;     
import android.content.IntentFilter;    
import android.net.wifi.ScanResult;    
import android.net.wifi.WifiConfiguration;   
import android.net.wifi.WifiConfiguration.AuthAlgorithm;
import android.net.wifi.WifiConfiguration.GroupCipher;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiConfiguration.PairwiseCipher;
import android.net.wifi.WifiConfiguration.Protocol;
import android.net.wifi.WifiManager;    
import android.os.Bundle;    
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;   
import android.view.LayoutInflater;
import android.view.View;    
import android.view.View.OnClickListener;    
import android.view.ViewGroup;
import android.widget.AdapterView;    
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;    
import android.widget.EditText;
import android.widget.ListView;    
import android.widget.SimpleAdapter;    
import android.widget.TextView;    
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements OnClickListener
 {      
    WifiManager wifi;       
    ListView lv;
//    TextView textStatus;
    Button buttonScan;
    int size = 0;
    List<ScanResult> results;
    final Context context = this;
    EditText pass;
    String checkPassword = null;

    String ITEM_KEY = "key";
    ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
    SimpleAdapter adapter;

    /* Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

//        textStatus = (TextView) findViewById(R.id.textStatus);
        buttonScan = (Button) findViewById(R.id.buttonScan);
        buttonScan.setOnClickListener(this);
        lv = (ListView)findViewById(R.id.list);
        lv.setOnItemClickListener(new OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
                connectToWifi(arg2);
            }



                private void connectToWifi(final int position)
                        {
                    final Dialog dialog = new Dialog(context);
                    dialog.setContentView(R.layout.connect);
                    dialog.setTitle("Connect to Network");
                    TextView textSSID = (TextView) dialog.findViewById(R.id.textSSID);
                    TextView textBSSID = (TextView) dialog.findViewById(R.id.textBSSID);
                    TextView capabilities = (TextView) dialog.findViewById(R.id.textCapabilities);

                    Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
                    pass = (EditText) dialog.findViewById(R.id.textPassword);
                    textSSID.setText(results.get(position).SSID);
                    textBSSID.setText(results.get(position).BSSID);
                    capabilities.setText(results.get(position).capabilities);
//                                      
                    // if button is clicked, connect to the network;
                    dialogButton.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            checkPassword = pass.getText().toString();
                            finallyConnect(checkPassword);
                            dialog.dismiss();
                        }

                        private void finallyConnect(String checkPassword) {
                            String networkSSID = results.get(position).SSID;
                            String networkPass = checkPassword;

                            WifiConfiguration wifiConfig = new WifiConfiguration();
                            wifiConfig.SSID = String.format("\"%s\"", networkSSID);
                            wifiConfig.preSharedKey = String.format("\"%s\"", networkPass);

                            WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
                            //remember id
                            int netId = wifiManager.addNetwork(wifiConfig);
                            wifiManager.disconnect();
                            wifiManager.enableNetwork(netId, true);
                            wifiManager.reconnect();



                            WifiConfiguration conf = new WifiConfiguration();
                            conf.SSID = "\"\"" + networkSSID + "\"\"";
                            conf.preSharedKey = "\""+ networkPass +"\"";
                            WifiManager wifiManager1 = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); 
                            wifiManager1.addNetwork(conf);

//                          List<WifiConfiguration> list = wifiManager1.getConfiguredNetworks();
//                          for( WifiConfiguration i : list ) {
//                              if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
//                                   wifiManager1.disconnect();
//                                   
//                                  wifiManager1.enableNetwork(i.networkId, true);
//                                  if(wifiManager1.reconnect()){
////                                    int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
////                                    Toast.makeText(getApplicationContext(), ipAddress, Toast.LENGTH_SHORT).show();
//                                  Toast.makeText(getApplicationContext(), networkSSID + " "+ "Connection successful", Toast.LENGTH_SHORT).show();                              
//                                  }
//                                  else{
//                                  Toast.makeText(getApplicationContext(), "Connection Failed", Toast.LENGTH_SHORT).show();
//                                  }
//                                  
//                                   break;
//                                         
//                              }
//                          }

                        }
                    });
                    dialog.show();
                }
       });

        lv.setOnItemLongClickListener(new OnItemLongClickListener(){

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub
                showWifiSettings(arg2);
                return true;
            }

            private void showWifiSettings(int arg2) {
                showDialogOfOptions(arg2);
                    }

            private void showDialogOfOptions(int arg2) {
                // Create a custom Dialog
                final Dialog dialog = new Dialog(context);
                dialog.setContentView(R.layout.custom);
                dialog.setTitle("Network details");
                TextView textSSID = (TextView) dialog.findViewById(R.id.textSSID);
                TextView textBSSID = (TextView) dialog.findViewById(R.id.textBSSID);
                Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
                textSSID.setText(results.get(arg2).SSID);
                textBSSID.setText(results.get(arg2).BSSID);
                // if button is clicked, close the custom dialog
                dialogButton.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });

                dialog.show();
              }
            });

        wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (wifi.isWifiEnabled() == false)
        {
            Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
            wifi.setWifiEnabled(true);
        }   

        this.adapter = new SimpleAdapter(MainActivity.this, arraylist, R.layout.row, new String[] { ITEM_KEY }, new int[] { R.id.list_value });
        lv.setAdapter(this.adapter);

        registerReceiver(new BroadcastReceiver()
        {
            @Override
            public void onReceive(Context c, Intent intent) 
            {
               results = wifi.getScanResults();
               size = results.size();
            }
        }, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));                    
    }

//    protected void connectionStatus(String password) {
//      // TODO Auto-generated method stub
//      
//      
//  }

    public void onClick(View view) 
    {


        arraylist.clear();          
        wifi.startScan();

        Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
        try 
        {
            size = size - 1;
            while (size >= 0) 
            {   
                HashMap<String, String> item = new HashMap<String, String>();
                item.put(ITEM_KEY, results.get(size).SSID.toString()+ results.get(size).capabilities.toString());

                arraylist.add(item);
                size--;
                adapter.notifyDataSetChanged();                 
            }


           }
        catch (Exception e)
        { }         
    }    
}

The application is running fine, but it does not connect to any of the Wifi networks. Any help please ?

balaji koduri
import java.util.ArrayList;
import java.util.HashMap;

import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
    private WifiManager wifi;
    private ListView lv;
    // TextView textStatus;
    private Button buttonScan;
    private int size = 0;
    private List<ScanResult> results;
    private final Context context = this;
    private EditText pass;
    private String checkPassword = null;

    private String ITEM_KEY = "key";
    private ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
    private SimpleAdapter adapter;
/* Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // textStatus = (TextView) findViewById(R.id.textStatus);
    buttonScan = (Button) findViewById(R.id.buttonScan);
    buttonScan.setOnClickListener(this);
    lv = (ListView) findViewById(R.id.list);
    wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            connectToWifi(arg2);
        }

    });

    lv.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {
            // TODO Auto-generated method stub
            showWifiSettings(arg2);
            return true;
        }
    });

    if (wifi.isWifiEnabled() == false) {
        Toast.makeText(getApplicationContext(),
                "wifi is disabled..making it enabled", Toast.LENGTH_LONG)
                .show();
        wifi.setWifiEnabled(true);
    }

    adapter = new SimpleAdapter(MainActivity.this, arraylist,
            R.layout.row, new String[] { ITEM_KEY },
            new int[] { R.id.list_value });
    lv.setAdapter(adapter);

    registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context c, Intent intent) {
            results = wifi.getScanResults();
            size = results.size();
        }
    }, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}

// protected void connectionStatus(String password) {
// // TODO Auto-generated method stub
//
//
// }
@Override
public void onClick(View view) {

    arraylist.clear();
    wifi.startScan();

    Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
    try {
        size = size - 1;
        while (size >= 0) {
            HashMap<String, String> item = new HashMap<String, String>();
            item.put(ITEM_KEY,
                    results.get(size).SSID.toString()
                            + results.get(size).capabilities.toString());

            arraylist.add(item);
            size--;
            adapter.notifyDataSetChanged();
        }

    } catch (Exception e) {
    }
}

private void showWifiSettings(int arg2) {
    showDialogOfOptions(arg2);
}

private void showDialogOfOptions(int arg2) {
    // Create a custom Dialog
    final Dialog dialog = new Dialog(context);
    dialog.setContentView(R.layout.custom);
    dialog.setTitle("Network details");
    TextView textSSID = (TextView) dialog.findViewById(R.id.textSSID);
    TextView textBSSID = (TextView) dialog.findViewById(R.id.textBSSID);
    Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
    textSSID.setText(results.get(arg2).SSID);
    textBSSID.setText(results.get(arg2).BSSID);
    // if button is clicked, close the custom dialog
    dialogButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });

    dialog.show();
}

private void finallyConnect(String checkPassword, int position) {
    String networkSSID = results.get(position).SSID;
    String networkPass = checkPassword;

    WifiConfiguration wifiConfig = new WifiConfiguration();
    wifiConfig.SSID = String.format("\"%s\"", networkSSID);
    wifiConfig.preSharedKey = String.format("\"%s\"", networkPass);

    // remember id
    int netId = wifi.addNetwork(wifiConfig);
    wifi.disconnect();
    wifi.enableNetwork(netId, true);
    wifi.reconnect();

    WifiConfiguration conf = new WifiConfiguration();
    conf.SSID = "\"\"" + networkSSID + "\"\"";
    conf.preSharedKey = "\"" + networkPass + "\"";
    wifi.addNetwork(conf);

    // List<WifiConfiguration> list =
    // wifiManager1.getConfiguredNetworks();
    // for( WifiConfiguration i : list ) {
    // if(i.SSID != null && i.SSID.equals("\"" + networkSSID
    // + "\"")) {
    // wifiManager1.disconnect();
    //
    // wifiManager1.enableNetwork(i.networkId, true);
    // if(wifiManager1.reconnect()){
    // // int ipAddress =
    // wifiManager.getConnectionInfo().getIpAddress();
    // // Toast.makeText(getApplicationContext(), ipAddress,
    // Toast.LENGTH_SHORT).show();
    // Toast.makeText(getApplicationContext(), networkSSID +
    // " "+ "Connection successful",
    // Toast.LENGTH_SHORT).show();
    // }
    // else{
    // Toast.makeText(getApplicationContext(),
    // "Connection Failed", Toast.LENGTH_SHORT).show();
    // }
    //
    // break;
    //
    // }
    // }

}

private void connectToWifi(final int position) {
    final Dialog dialog = new Dialog(context);
    dialog.setContentView(R.layout.connect);
    dialog.setTitle("Connect to Network");
    TextView textSSID = (TextView) dialog.findViewById(R.id.textSSID1);
    TextView textBSSID = (TextView) dialog.findViewById(R.id.textBSSID1);
    TextView capabilities = (TextView) dialog
            .findViewById(R.id.textCapabilities);

    Button dialogButton = (Button) dialog.findViewById(R.id.okButton);
    pass = (EditText) dialog.findViewById(R.id.textPassword);
    textSSID.setText(results.get(position).SSID);
    textBSSID.setText(results.get(position).BSSID);
    capabilities.setText(results.get(position).capabilities);
    //
    // if button is clicked, connect to the network;
    dialogButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            checkPassword = pass.getText().toString();
            finallyConnect(checkPassword, position);
            dialog.dismiss();
        }

    });
    dialog.show();
}

}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Re: Connect to a wifi network programmatically

From Dev

Unable to connect to a specific Wifi network programmatically on Android

From Dev

How to connect to WiFi programmatically

From Dev

Android connect to Wifi programmatically if wifi name match

From Dev

How to connect android device to "WPA2 PSK" secured wifi hotspot network programmatically?

From Dev

Automatically connect to wifi network in android?

From Dev

Cannot connect to home WiFi network

From Dev

Connect to Enterprise WiFi network issue

From Dev

Unable to connect to specific wifi network

From Dev

How to connect to a wireless network programmatically?

From Dev

Getting data speed of wifi/mobile network programmatically

From Java

Connect to WiFi Access Point programmatically with Android 10

From Dev

Programmatically connect or detect to a certain WiFi in iOS?

From Dev

Automatically connect to wifi network when no internet detected

From Dev

connect to a wifi network using batch or vb script

From Dev

Wifi card can see network but cannot connect

From Dev

simple python script to scan and connect wifi network

From Dev

How can I connect to a specific wifi network?

From Dev

How to connect to hidden wifi network using nmcli

From Dev

Wifi card can see network but cannot connect

From Dev

Lubuntu / Ubuntu - Unable to connect to wifi network

From Dev

Cannot connect to WiFi network on Windows 8 / 8.1

From Dev

Connect to WiFi network using Mac Terminal

From Dev

Can a laptop connect to an ethernet network printer with WIFI?

From Dev

Cannot connect to WiFi network wirelessly using Broadcom

From Dev

How can I connect to a specific wifi network?

From Dev

How to connect 3 wifi routers in a home network

From Dev

Ubuntu Server 16.04: connect to wifi network (usb wifi adapter)

From Dev

Ubuntu Server 16.04: connect to wifi network (usb wifi adapter)

Related Related

  1. 1

    Re: Connect to a wifi network programmatically

  2. 2

    Unable to connect to a specific Wifi network programmatically on Android

  3. 3

    How to connect to WiFi programmatically

  4. 4

    Android connect to Wifi programmatically if wifi name match

  5. 5

    How to connect android device to "WPA2 PSK" secured wifi hotspot network programmatically?

  6. 6

    Automatically connect to wifi network in android?

  7. 7

    Cannot connect to home WiFi network

  8. 8

    Connect to Enterprise WiFi network issue

  9. 9

    Unable to connect to specific wifi network

  10. 10

    How to connect to a wireless network programmatically?

  11. 11

    Getting data speed of wifi/mobile network programmatically

  12. 12

    Connect to WiFi Access Point programmatically with Android 10

  13. 13

    Programmatically connect or detect to a certain WiFi in iOS?

  14. 14

    Automatically connect to wifi network when no internet detected

  15. 15

    connect to a wifi network using batch or vb script

  16. 16

    Wifi card can see network but cannot connect

  17. 17

    simple python script to scan and connect wifi network

  18. 18

    How can I connect to a specific wifi network?

  19. 19

    How to connect to hidden wifi network using nmcli

  20. 20

    Wifi card can see network but cannot connect

  21. 21

    Lubuntu / Ubuntu - Unable to connect to wifi network

  22. 22

    Cannot connect to WiFi network on Windows 8 / 8.1

  23. 23

    Connect to WiFi network using Mac Terminal

  24. 24

    Can a laptop connect to an ethernet network printer with WIFI?

  25. 25

    Cannot connect to WiFi network wirelessly using Broadcom

  26. 26

    How can I connect to a specific wifi network?

  27. 27

    How to connect 3 wifi routers in a home network

  28. 28

    Ubuntu Server 16.04: connect to wifi network (usb wifi adapter)

  29. 29

    Ubuntu Server 16.04: connect to wifi network (usb wifi adapter)

HotTag

Archive