Android开发,连接到指定WIFI

来源:互联网 发布:linux shell 输入 编辑:程序博客网 时间:2024/06/05 08:08
//拿到WifiManagerWifiManager 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();        }    }}
0 0
原创粉丝点击