Android开发,连接到指定WIFI

//拿到WifiManager
WifiManager wifiManager = (WifiManager) MainActivity.this
                                        .getSystemService(Context.WIFI_SERVICE);

//判断wifi是否打开
if (!wifiManager.isWifiEnabled()) {
    wifiManager.setWifiEnabled(true);
}
//因为打开需要时间,所以要等一下
while (!wifiManager.isWifiEnabled()) {
        SystemClock.sleep(100);
}

// wifi的conf参数
WifiConfiguration conf = new WifiConfiguration();
//连接WAP时,设置如下
conf.SSID = "\"" + networkSSID + "\"";
conf.preSharedKey = "\"" + networkPass + "\"";
// 连接公网时设置如下
// conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
//如果是WEP的加密协议,就用如下设置
//conf.wepKeys[0] = "\"" + networkPass + "\""; 
//conf.wepTxKeyIndex = 0;
//conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
//conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
// 把wifi的conf参数设置进来
wifiManager.addNetwork(conf);
// 获得wifi列表里面的所有wifi连接,如果连接的不是我们要连接的wifi,就重新连接
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();

for (WifiConfiguration i : list) {
    Log.d(TAG, "ssid" + i.SSID);
    if (i.SSID != null&& i.SSID.equals("\"" + networkSSID + "\"")) {
        Log.d(TAG, networkSSID + "------" + networkPass);
        wifiManager.disconnect();
        wifiManager.enableNetwork(i.networkId, true);
        boolean reconnect = wifiManager.reconnect();
        //连接出错,跳转
        if (!reconnect) {
            Intent intent = new Intent(getApplicationContext(),ErrorActivity.class);
            startActivity(intent);
            finish();
        }
    }
}

你可能感兴趣的:(Android功能,android开发,wi-fi)