Android 设置连接隐藏到网络

600 阅读1分钟

背景:需要向其他人隐藏wifi名称,然后特定情况下应用自动连接此隐藏wifi

首先,需要知道wifi的ssid、password

 WifiConfiguration conf = new WifiConfiguration();
 Log.d("Aut", param.getSsid() + " : " + param.getPasswd());
 conf.SSID = """ + param.getSsid() + """;
 conf.preSharedKey = """ + param.getPasswd() + """;
 conf.hiddenSSID = true; // Put this line to hidden SSID
 conf.status = WifiConfiguration.Status.ENABLED;
 conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
 conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
 conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
 conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
 conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
 conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);

 // Connect Network

// this.wifiManager =(WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
 assert mWifiManager != null;

 int netId = mWifiManager.addNetwork(conf);
 WifiInfo wifi_inf = mWifiManager.getConnectionInfo();
 mWifiManager.disableNetwork(wifi_inf.getNetworkId());
 mWifiManager.enableNetwork(netId, true);
 mWifiManager.reconnect();

注意添加 conf.hiddenSSID = true; // Put this line to hidden SSID,一般的网络连接是先要从能够搜到ssid的网络中去添加,然后进行enableNetwork,但是如果是隐藏掉的wifi,搜不到此名称,连接还是会失败