无法以编程方式连接所需的Wifi网络

时间:2017-09-13 06:18:16

标签: android android-wifi

我正在使用以下代码扫描并连接我想要的网络。如果我的网络已经连接,它可以正常工作,在这种情况下,当我点击我的扫描按钮时,它会断开连接并重新连接。但是当没有连接网络且wifi打开时,它就无法连接。可能是什么问题。任何建议都将受到高度赞赏。

WifiBroadCastReceiver:

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.SupplicantState;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.widget.Toast;

import java.util.List;

public class WifiBroadReceiver extends BroadcastReceiver {

    final static String networkSSID = "myDevice";
    final static String networkPass = "password";
    Context context;

    @Override
    public void onReceive(Context context, Intent intent) {
        this.context = context;
        String action = intent.getAction();
        if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(action)) {
            SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);

            if (SupplicantState.isValidState(state)
                    && (
                    state == SupplicantState.COMPLETED
                            || state == SupplicantState.DISCONNECTED
                            || state == SupplicantState.SCANNING
            )) {

                boolean connected = checkConnectedToDesiredWifi();

                if (!connected) {
                    try {
                        addMyNetwork(context);
                    } catch (Exception e) {
                    }
                }
            }
        }
    }

    /**
     * Detect you are connected to a specific network.
     */
    private boolean checkConnectedToDesiredWifi() {
        boolean connected = false;

        String desiredMacAddress = networkSSID;

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

        WifiInfo wifi = wifiManager.getConnectionInfo();
        if (wifi != null) {
            // get current router Mac address
            String bssid = wifi.getBSSID();
            connected = desiredMacAddress.equals(bssid);
              }

        return connected;
    }


    private void addMyNetwork(Context context) {

        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + networkSSID + "\"";   // Please note the quotes. String should contain ssid in quotes
        //Then, for WEP network you need to do this
        conf.wepKeys[0] = "\"" + networkPass + "\"";
        conf.wepTxKeyIndex = 0;
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
        //For WPA network you need to add passphrase like this:
        conf.preSharedKey = "\"" + networkPass + "\"";
        //For Open network you need to do this:
        //conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

        //  Then, you need to add it to Android wifi manager settings:
        WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        //--------
        wifiManager.setWifiEnabled(true);

        wifiManager.addNetwork(conf);

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

}

onButtonClick:

public void onWifiClick(View view) {

        BroadcastReceiver broadcastReceiver = new WifiBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        registerReceiver(broadcastReceiver, intentFilter);
    }

1 个答案:

答案 0 :(得分:0)

请在这里查看我的答案是否为optimal solution !,该产品已经过测试,并适用于Oreo +

快乐编码!