【问题标题】:unable to connect with desired Wifi Network programmatically无法以编程方式连接所需的 Wifi 网络
【发布时间】:2019-06-03 14:04:26
【问题描述】:

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

WifiBroadCast接收器:

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

}

点击按钮:

public void onWifiClick(View view) {

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

【问题讨论】:

  • addMyNetwork 会被调用吗?
  • 这不是 Android Studio 问题。不要使用那个标签
  • @VladMatvienko 是的,它被调用了。

标签: android android-wifi


【解决方案1】:

请在此处查看我的答案以获取 optimal solution!,经过测试并适用于 Oreo+

编码愉快!

【讨论】:

    猜你喜欢
    • 2023-01-27
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多