无法在Android上以编程方式连接到特定的Wifi网络

时间:2016-01-26 09:35:18

标签: android

我想设计一个应用程序,显示可用的无线网络列表,并在选择时连接到网络。我已经实现了显示扫描结果的部分。现在,我想从扫描结果列表连接到用户选择的特定网络。谁能告诉我怎么做?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ListView listview = (ListView) findViewById(R.id.listView);

    adapter = new ArrayAdapter
            (this, android.R.layout.simple_list_item_1);

    listview.setAdapter(adapter);

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

    wifiReciever = new WiFiScanReceiver();


}

public void onToggleClicked(View view) {

    adapter.clear();

    ToggleButton toggleButton = (ToggleButton) view;

    if (wifiManager == null) {
        // Device does not support Wi-Fi
        Toast.makeText(getApplicationContext(), "Oop! Your device does not support Wi-Fi",
                Toast.LENGTH_SHORT).show();
        toggleButton.setChecked(false);

    } else {
        if (toggleButton.isChecked()) { // To turn on Wi-Fi
            if (!wifiManager.isWifiEnabled()) {

                Toast.makeText(getApplicationContext(), "Wi-Fi is turned on." +
                                "\n" + "Scanning for access points...",
                        Toast.LENGTH_SHORT).show();

                wifiManager.setWifiEnabled(true);

            } else {
                Toast.makeText(getApplicationContext(), "Wi-Fi is already turned on." +
                                "\n" + "Scanning for access points...",
                        Toast.LENGTH_SHORT).show();
            }
            wifiManager.startScan();

        } else { // To turn off Wi-Fi
            Toast.makeText(getApplicationContext(), "Wi-Fi is turned off.",
                    Toast.LENGTH_SHORT).show();
            wifiManager.setWifiEnabled(false);
        }
    }


}

class WiFiScanReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        //if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
        //    wifiScanResult = wifiManager.getScanResults();


        if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
            List<ScanResult> wifiScanResultList = wifiManager.getScanResults();
            for (int i = 0; i < wifiScanResultList.size(); i++) {
                ScanResult accessPoint = wifiScanResultList.get(i);
                //wifiScanList[i] = wifiScanResultList.get(i).SSID;
                String listItem = " Name: " + accessPoint.SSID +    " \n Mac: " + accessPoint.BSSID + "\n Signal Strenght: " + accessPoint.level+ "dBm";
                adapter.add(listItem);
                // }
                // }
                //listview.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, wifiScanList));


            }
        }


    }
}








@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(wifiReciever);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.wi_fi, 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();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

3 个答案:

答案 0 :(得分:1)

在列表视图中选择的每个项目上启动此方法:

  static public void ConnectToWiFi(String ssid ,String key,Context ctx) {

    WifiConfiguration wifiConfig = new WifiConfiguration();
    wifiConfig.SSID = String.format("\"%s\"", ssid);
    wifiConfig.preSharedKey = String.format("\"%s\"", key);
    WifiManager wifiManager = (WifiManager) ctx.getSystemService(ctx.WIFI_SERVICE);
    int networkId = wifiManager.getConnectionInfo().getNetworkId();
    wifiManager.removeNetwork(networkId);
    wifiManager.saveConfiguration();
    //remember id
    int netId = wifiManager.addNetwork(wifiConfig);
    wifiManager.disconnect();
    wifiManager.enableNetwork(netId, true);
    wifiManager.reconnect();
}

输入项目的SSID和密钥/密码,如果不需要,您可以删除上下文 祝你好运

答案 1 :(得分:0)

以下链接将是您了解Android WiFi Manager并连接到特定网络的良好起点。

  1. How to connect to a specific WiFi network

  2. Create and manage WiFi Configurations

  3. 希望这有帮助。

答案 2 :(得分:0)

接受的答案不适用于Oreo +!我们需要正确指定wificonfig以连接到特定的Wifi网络。 我有类似的用例,我确实使用一些常识来解决。我们要连接的wifi应该可以使用,对吗?这意味着,如果我们扫描wifi管理器,则在ScanResult列表中应该有SSID == MySSID的设备。在此匹配的scanResult中,我们还具有扫描项所拥有的安全性类型,这将有助于我们进行更多的设置。专用于WPA2和WEP的WifiConfig,有意义吗?

好的,所以我们一步一步来!  1.创建一个Wifi管理器实例,然后像

一样对其调用startScan
  

mWifiManager.startScan()

,调用此方法后,将通过BroadcastReceiver接收可用设备的扫描列表,其OnReceive如下所示:

if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
            List<ScanResult> mScanResults = mWifiManager.getScanResults();
            for (ScanResult res :
                    mScanResults) {
                if (!isConnected && res.SSID.contains(networkSSID)) {
                    networkSSID = res.SSID;
                    connectthis(res);
                }
            }

2。该连接方法应如下所示:

private void connectthis(ScanResult res) {
    Context context = getApplicationContext();
    WifiConfiguration wifiConfig = new WifiConfiguration();
    wifiConfig.SSID = String.format("\"%s\"", res.SSID);
    wifiConfig.BSSID = res.BSSID;
    wifiConfig.priority = 40;
    if (res.capabilities.toLowerCase().contains("wep")) {
        wifiConfig.wepKeys[0] = String.format("\"%s\"", networkKey);
        wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
        wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
        wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
        wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
        wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
    } else if (res.capabilities.toLowerCase().contains("wpa")) {
        wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
        wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
        wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
        wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        wifiConfig.preSharedKey = String.format("\"%s\"", networkKey);
    }


    if (networkKey.equalsIgnoreCase(""))
        wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    WifiManager wifiManager = 
   (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
    boolean isConfigured = false;
    List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
    for (WifiConfiguration i : list) {
        if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
            wifiManager.disconnect();
            wifiManager.enableNetwork(i.networkId, true);
            wifiManager.reconnect();
            isConfigured = true;
            break;
        }
    }
    //adding the network
    if (!isConfigured) {
        int netId = wifiManager.addNetwork(wifiConfig);
        wifiManager.saveConfiguration();
        wifiManager.disconnect();
        wifiManager.enableNetwork(netId, true);
    }
}

希望有帮助!