如何以编程方式连接到Android中的特定Wi-Finetworking?
我想devise一个应用程序,显示可用的Wi-Finetworking列表,并连接到用户select的任何networking。
我已经实现了显示扫描结果的部分。 现在我想连接到用户从扫描结果列表中select的特定networking。
我如何做到这一点?
您需要像这样创buildWifiConfiguration
实例:
String networkSSID = "test"; String networkPass = "pass"; WifiConfiguration conf = new WifiConfiguration(); conf.SSID = "\"" + networkSSID + "\""; // Please note the quotes. String should contain ssid in quotes
那么,对于WEPnetworking,您需要这样做:
conf.wepKeys[0] = "\"" + networkPass + "\""; conf.wepTxKeyIndex = 0; conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
对于WPAnetworking,您需要添加如下所示的密码:
conf.preSharedKey = "\""+ networkPass +"\"";
对于开放networking,您需要这样做:
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
然后,你需要把它添加到Android的WiFipipe理器设置:
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); wifiManager.addNetwork(conf);
最后,您可能需要启用它,所以Android连接到它:
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; } }
UPD:在WEP的情况下,如果你的密码是hex的,你不需要用引号包围它。
较早的答案有效 ,但解决scheme实际上可以更简单。 在通过WifiManager添加networking时,通过configuration的networking列表进行循环列表并不是必需的,因为您可以获取networking标识。
所以完整的简化解决scheme看起来像这样:
WifiConfiguration wifiConfig = new WifiConfiguration(); wifiConfig.SSID = String.format("\"%s\"", ssid); wifiConfig.preSharedKey = String.format("\"%s\"", key); WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE); //remember id int netId = wifiManager.addNetwork(wifiConfig); wifiManager.disconnect(); wifiManager.enableNetwork(netId, true); wifiManager.reconnect();
在连接WIFInetworking之前,您需要检查WIFInetworkingScanResult类的安全types是否具有function。 这个字段给你的networkingtypes
请参阅: https : //developer.android.com/reference/android/net/wifi/ScanResult.html#capabilities
有三种types的WIFInetworking。
首先,实例化一个WifiConfiguration对象并填入networking的SSID(注意,它必须用双引号括起来),将初始状态设置为禁用,并指定networking的优先级(数字大约为40)。
WifiConfiguration wfc = new WifiConfiguration(); wfc.SSID = "\"".concat(ssid).concat("\""); wfc.status = WifiConfiguration.Status.DISABLED; wfc.priority = 40;
现在对于更复杂的部分:我们需要填写WifiConfiguration的几个成员来指定networking的安全模式。 对于开放networking。
wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN); wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA); wfc.allowedAuthAlgorithms.clear(); wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
对于使用WEP的networking; 请注意,WEP密钥也用双引号括起来。
wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN); wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA); wfc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); wfc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); if (isHexString(password)) wfc.wepKeys[0] = password; else wfc.wepKeys[0] = "\"".concat(password).concat("\""); wfc.wepTxKeyIndex = 0;
对于使用WPA和WPA2的networking,我们可以设置相同的值。
wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN); wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA); wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); wfc.preSharedKey = "\"".concat(password).concat("\"");
最后,我们可以将networking添加到WifiManager的已知列表中
WifiManager wfMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); int networkId = wfMgr.addNetwork(wfc); if (networkId != -1) { // success, can call wfMgr.enableNetwork(networkId, true) to connect }
感谢@ raji-ramamoorthi&@kenota
为我工作的解决scheme是在这个线程的上述贡献者的组合。
在这里获取ScanResult
是这个过程。
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); if (wifi.isWifiEnabled() == false) { Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show(); wifi.setWifiEnabled(true); } BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context c, Intent intent) { wifi.getScanResults(); } };
注意在onPause
& onStop
上unregister
它,这个unregisterReceiver(broadcastReceiver);
public void connectWiFi(ScanResult scanResult) { try { Log.v("rht", "Item clicked, SSID " + scanResult.SSID + " Security : " + scanResult.capabilities); String networkSSID = scanResult.SSID; String networkPass = "12345678"; WifiConfiguration conf = new WifiConfiguration(); conf.SSID = "\"" + networkSSID + "\""; // Please note the quotes. String should contain ssid in quotes conf.status = WifiConfiguration.Status.ENABLED; conf.priority = 40; if (scanResult.capabilities.toUpperCase().contains("WEP")) { Log.v("rht", "Configuring WEP"); conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN); conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA); conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); if (networkPass.matches("^[0-9a-fA-F]+$")) { conf.wepKeys[0] = networkPass; } else { conf.wepKeys[0] = "\"".concat(networkPass).concat("\""); } conf.wepTxKeyIndex = 0; } else if (scanResult.capabilities.toUpperCase().contains("WPA")) { Log.v("rht", "Configuring WPA"); conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN); conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA); conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); conf.preSharedKey = "\"" + networkPass + "\""; } else { Log.v("rht", "Configuring OPEN network"); conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN); conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA); conf.allowedAuthAlgorithms.clear(); conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); } WifiManager wifiManager = (WifiManager) WiFiApplicationCore.getAppContext().getSystemService(Context.WIFI_SERVICE); int networkId = wifiManager.addNetwork(conf); Log.v("rht", "Add result " + networkId); List<WifiConfiguration> list = wifiManager.getConfiguredNetworks(); for (WifiConfiguration i : list) { if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) { Log.v("rht", "WifiConfiguration SSID " + i.SSID); boolean isDisconnected = wifiManager.disconnect(); Log.v("rht", "isDisconnected : " + isDisconnected); boolean isEnabled = wifiManager.enableNetwork(i.networkId, true); Log.v("rht", "isEnabled : " + isEnabled); boolean isReconnected = wifiManager.reconnect(); Log.v("rht", "isReconnected : " + isReconnected); break; } } } catch (Exception e) { e.printStackTrace(); } }
这是一个活动,你可以inheritance强制连接到一个特定的WiFi: https : //github.com/zoltanersek/android-wifi-activity/blob/master/app/src/main/java/com/zoltanersek/androidwifiactivity/ WifiActivity.java
您将需要inheritance此活动并实现其方法:
public class SampleActivity extends WifiBaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected int getSecondsTimeout() { return 10; } @Override protected String getWifiSSID() { return "WifiNetwork"; } @Override protected String getWifiPass() { return "123456"; } }
我打破了我的头,了解为什么你的WPA / WPA2的答案不工作…经过几个小时的尝试,我发现你所缺less的:
conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
是必需的WPAnetworking!
现在,它的工作:)
试试这个方法。 这很简单:
public static boolean setSsidAndPassword(Context context, String ssid, String ssidPassword) { try { WifiManager wifiManager = (WifiManager) context.getSystemService(context.WIFI_SERVICE); Method getConfigMethod = wifiManager.getClass().getMethod("getWifiApConfiguration"); WifiConfiguration wifiConfig = (WifiConfiguration) getConfigMethod.invoke(wifiManager); wifiConfig.SSID = ssid; wifiConfig.preSharedKey = ssidPassword; Method setConfigMethod = wifiManager.getClass().getMethod("setWifiApConfiguration", WifiConfiguration.class); setConfigMethod.invoke(wifiManager, wifiConfig); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
如果您的设备知道Wificonfiguration(已存储),我们可以绕过火箭科学。 只要通过configuration循环检查SSID是否匹配。 如果是这样,连接并返回 。
设置权限:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
连接:
try { String ssid = null; if (wifi == Wifi.PCAN_WIRELESS_GATEWAY) { ssid = AesPrefs.get(AesConst.PCAN_WIRELESS_SSID, context.getString(R.string.pcan_wireless_ssid_default)); } else if (wifi == Wifi.KJ_WIFI) { ssid = context.getString(R.string.remote_wifi_ssid_default); } WifiManager wifiManager = (WifiManager) context.getApplicationContext() .getSystemService(Context.WIFI_SERVICE); List<WifiConfiguration> wifiConfigurations = wifiManager.getConfiguredNetworks(); for (WifiConfiguration wifiConfiguration : wifiConfigurations) { if (wifiConfiguration.SSID.equals("\"" + ssid + "\"")) { wifiManager.enableNetwork(wifiConfiguration.networkId, true); Log.i(TAG, "connectToWifi: will enable " + wifiConfiguration.SSID); wifiManager.reconnect(); return null; // return! (sometimes logcat showed me network-entries twice, // which may will end in bugs) } } } catch (NullPointerException | IllegalStateException e) { Log.e(TAG, "connectToWifi: Missing network configuration."); } return null;