Re:以编程方式连接到wifi网络

时间:2014-07-01 10:35:49

标签: android networking android-wifi

我希望创建一个应用程序,它可以检测附近的可用wifi连接,然后连接到它们。我到目前为止所做的是,我创建了一个ListView,列出了可用的wifi连接,然后我创建了一个LongItemClick对话框,显示网络的SSID和BSSID,并要求输入密码。现在,我希望连接到其中一个网络,不管它是什么类型的网络,它也可能是WEP,WPA或Open。我无法概述如何连接它们。谁能帮我这个 ?我搜索了所有可用的答案,但我没有找到任何答案,这可以帮助我做到这一点!

我通过以下方法尝试上述事情。我创建了附近所有可用的Wi-Fi网络的列表视图,然后我尝试在长按时显示连接信息,并通过点击提供连接到点击的Wi-Fi网络的选项。

代码:

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)
        { }         
    }    
}

应用程序运行正常,但它没有连接到任何Wifi网络。有什么帮助吗?

3 个答案:

答案 0 :(得分:2)

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();
}

}

答案 1 :(得分:0)

Hey BumbleBee我猜你做错了,

  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);

            for(int i=0;i<arraylist.size();i++)
            {
           Log.e("arraylist","items-->"+ arraylist.get(i));
                Log.e("arraylist", "sizze-->" + arraylist.size());
            }

            Log.e("item","hashmap item---> "+item);
            size--;

            adapter.notifyDataSetChanged();
        }
     catch (Exception e) {
    }
Instead try this,
            for(int k=0;k<size;k++){

            HashMap<String, String> item = new HashMap<String, String>();
            item.put(ITEM_KEY,
                    result_reference.get(k).SSID.toString()
                            + result_reference.get(k).capabilities.toString());

            arraylist.add(item);

            for(int i=0;i<arraylist.size();i++)
            {
                Log.e("arraylist","items-->"+ arraylist.get(i));
                Log.e("arraylist", "sizze-->" + arraylist.size());
            }

            // Log.e("item","hashmap item---> "+item);
           // size--;

            //adapter.notifyDataSetChanged();

        }
        lv.setAdapter(adapter);

    } catch (Exception e) {
    }

`

答案 2 :(得分:0)

此代码100%有效 它搜索可用的WiFi列表并将其显示在列表视图中,然后通过单击列表视图,将出现一个对话框,显示要输入的SSID,BSSID和密码。 它工作正常。

MainActivity:

import android.annotation.SuppressLint;

导入android.app.Dialog;

import android.content.BroadcastReceiver;

import android.content.Context;

导入android.content.Intent;

import android.content.IntentFilter;

导入android.net.wifi.ScanResult;

导入android.net.wifi.WifiConfiguration;

导入android.net.wifi.WifiManager;

import android.support.v7.app.AppCompatActivity;

导入android.os.Bundle;

导入android.view.Menu;

import android.view.MenuItem;

导入android.view.View;

导入android.widget.AdapterView;

import android.widget.ArrayAdapter;

导入android.widget.Button;

导入android.widget.EditText;

import android.widget.ListView;

import android.widget.SimpleAdapter;

导入android.widget.TextView;

导入android.widget.Toast;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

公共类MainActivity扩展了AppCompatActivity实现 View.OnClickListener {

private WifiManager wifi;

WifiScanReceiver wifiReciever;

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;

String wifis[];




@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    buttonScan = (Button) findViewById(R.id.buttonScan);

    buttonScan.setOnClickListener(this);

    lv = (ListView) findViewById(R.id.list);

    wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    wifiReciever = new WifiScanReceiver();

    wifi.startScan();


    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {

            // TODO Auto-generated method stub

            connectToWifi(arg2);
        }

    });

    lv.setOnItemLongClickListener(new AdapterView.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);
    }

    this.adapter = new SimpleAdapter(MainActivity.this, arraylist,
            R.layout.custom  , new String[] { ITEM_KEY },      //concentrate
            new int[] { R.id.list });
    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));
}

@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) {

    }
}
protected void onPause() {

    unregisterReceiver(wifiReciever);

    super.onPause();
}

protected void onResume() {

    registerReceiver(wifiReciever, new IntentFilter(
            WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

    super.onResume();

}


class WifiScanReceiver extends BroadcastReceiver {

    @SuppressLint("UseValueOf")

    public void onReceive(Context c, Intent intent) {

        List<ScanResult> wifiScanList = wifi.getScanResults();

        wifis = new String[wifiScanList.size()];

        for(int i = 0; i < wifiScanList.size(); i++){

            wifis[i] = ((wifiScanList.get(i)).toString());

        }

        String filtered[] = new String[wifiScanList.size()];

        int counter = 0;

        for (String eachWifi : wifis) {

            String[] temp = eachWifi.split(",");

            filtered[counter] = temp[0].substring(5).trim()+"\n" + temp[2].substring(12).trim()+"\n" +temp[3].substring(6).trim();//0->SSID, 2->Key Management 3-> Strength


            counter++;

        }

        lv.setAdapter(new ArrayAdapter<String>(getApplicationContext(),
                android.R.layout.simple_list_item_1, filtered));


    }

}

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.textSSID1);

    TextView textBSSID = (TextView) dialog.findViewById(R.id.textBSSID1);

    Button dialogButton = (Button) dialog.findViewById(R.id.okButton);

    textSSID.setText(results.get(arg2).SSID);

    textBSSID.setText(results.get(arg2).BSSID);

    // if button is clicked, close the custom dialog

    dialogButton.setOnClickListener(new View.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);
}

private void connectToWifi(final int position) {

    final Dialog dialog = new Dialog(context);

    dialog.setContentView(R.layout.custom);

    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 View.OnClickListener() {

        @Override

        public void onClick(View v) {

            checkPassword = pass.getText().toString();

            finallyConnect(checkPassword, position);

            dialog.dismiss();

        }

    });

    dialog.show();



}



@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override

public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

XML文件: activity_main.xml中

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="scan"
    android:id="@+id/buttonScan"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/list"
    android:layout_centerHorizontal="true"
    android:layout_below="@+id/buttonScan" />