如何连接到API级别29的特定Wifi连接?

时间:2019-11-09 17:20:47

标签: android wifi wificonfiguration

切换到API 29后,我无法连接到特定的wifi网络。我的旧代码是下面显示的代码,其中包含我编写的新代码。 我试图咨询www.developer.android.com但 我无法正常工作。当我请求连接到特定的wifi时,Android选择另一个wifi(例如:home)。 有人可以帮我吗?

 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {

        WifiNetworkSpecifier.Builder builder = new WifiNetworkSpecifier.Builder();
        builder.setSsid(ssid);
        builder.setWpa2Passphrase(key);

        WifiNetworkSpecifier wifiNetworkSpecifier = builder.build();

        NetworkRequest.Builder networkRequestBuilder = new NetworkRequest.Builder();
        networkRequestBuilder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
        networkRequestBuilder.setNetworkSpecifier(wifiNetworkSpecifier);

        NetworkRequest networkRequest = networkRequestBuilder.build();
        ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        cm.requestNetwork(networkRequest, new ConnectivityManager.NetworkCallback());
    }else{
        wifiConfig.SSID = String.format("\"%s\"", ssid);
        wifiConfig.preSharedKey = String.format("\"%s\"", key);
        wifiConfig.priority = 40;
        WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
        int ssid  = wifiManager.getConnectionInfo().getIpAddress();
        Log.d("prova", ssid+"");
        if(ssid!=201631936) {
            wifiManager.setWifiEnabled(true);
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int netId = wifiManager.addNetwork(wifiConfig);
            wifiManager.disconnect();
            wifiManager.enableNetwork(netId, true);
            wifiManager.reconnect();
        }
    }

0 个答案:

没有答案