Example #1
1
 // 连接指定Id的WIFI
 public boolean ConnectWifi(int wifiId) {
   for (int i = 0; i < wifiConfigList.size(); i++) {
     WifiConfiguration wifi = wifiConfigList.get(i);
     if (wifi.networkId == wifiId) {
       while (!(localWifiManager.enableNetwork(wifiId, true))) { // 激活该Id,建立连接
         // status:0--已经连接,1--不可连接,2--可以连接
         Log.i(TAG, "status " + String.valueOf(wifiConfigList.get(wifiId).status));
       }
       return true;
     }
   }
   return false;
 }
  /**
   * connecting to wifi with provided credentials
   *
   * @param ssid - network identificator
   * @param password - network password
   * @return flag indicating wifi connection state
   */
  private boolean connectToWifi(String ssid, String password) {

    final String TAG_WIFI_CONNECTING = "connectingToWiFi";
    WifiManager wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);

    if (!wifi.isWifiEnabled()) {
      if (!wifi.setWifiEnabled(true)) {
        Log.e("WiFi", "without WiFi won't work");
        return false;
      }
    }

    WifiConfiguration conf = new WifiConfiguration();
    conf.SSID = "\"" + ssid + "\"";
    conf.preSharedKey = "\"" + password + "\"";
    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);
    conf.status = WifiConfiguration.Status.ENABLED;
    int networkId = wifi.addNetwork(conf);
    wifi.disconnect();
    wifi.enableNetwork(networkId, true);
    boolean completed = wifi.reconnect();

    if (!completed) {
      Log.d(TAG_WIFI_CONNECTING, "repeat wifi connection attempt");
      try {
        Thread.sleep(5000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      wifi.disconnect();
      wifi.enableNetwork(networkId, true);
      completed = wifi.reconnect();
    }

    /**
     * delay introduced in order to wait for establishing connection (flag from reconnect() is set
     * before network is really working)
     */
    try {
      Thread.sleep(5000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    if (completed) {
      (new Setup(getApplicationContext())).start();
      logEvent(CONFIGURATION_TAG, "connected to Wi-Fi");
    }

    return completed;
  }
Example #3
0
  /**
   * Connect to a configured network.
   *
   * @param wifiManager
   * @param config
   * @param numOpenNetworksKept Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT
   * @return
   */
  public boolean connectToConfiguredNetwork(WifiConfiguration config, boolean reassociate) {
    final String security = ConfigSec.getWifiConfigurationSecurity(config);
    int oldPri = config.priority;
    // Make it the highest priority.
    int newPri = getMaxPriority() + 1;
    if (newPri > MAX_PRIORITY) {
      newPri = shiftPriorityAndSave();
      config = getWifiConfiguration(config, security);
      if (config == null) {
        return false;
      }
    }

    // Set highest priority to this configured network
    config.priority = newPri;
    int networkId = mWifiManager.updateNetwork(config);
    if (networkId == -1) {
      return false;
    }

    // Do not disable others
    if (!mWifiManager.enableNetwork(networkId, false)) {
      config.priority = oldPri;
      return false;
    }

    if (!mWifiManager.saveConfiguration()) {
      config.priority = oldPri;
      return false;
    }

    // We have to retrieve the WifiConfiguration after save.
    config = getWifiConfiguration(config, security);
    if (config == null) {
      return false;
    }

    // ReenableAllApsWhenNetworkStateChanged.schedule(mContext);

    // Disable others, but do not save.
    // Just to force the WifiManager to connect to it.
    if (!mWifiManager.enableNetwork(config.networkId, true)) {
      return false;
    }

    final boolean connect = reassociate ? mWifiManager.reassociate() : mWifiManager.reconnect();
    if (!connect) {
      return false;
    }

    return true;
  }
Example #4
0
  public static void installConferenceWiFi(final Context context) {
    // Create config
    WifiConfiguration config = new WifiConfiguration();
    // Must be in double quotes to tell system this is an ASCII SSID and passphrase.
    config.SSID = String.format("\"%s\"", Config.WIFI_SSID);
    config.preSharedKey = String.format("\"%s\"", Config.WIFI_PASSPHRASE);

    // Store config
    final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    int netId = wifiManager.addNetwork(config);
    if (netId != -1) {
      wifiManager.enableNetwork(netId, false);
      boolean result = wifiManager.saveConfiguration();
      if (!result) {
        Log.e(TAG, "Unknown error while calling WiFiManager.saveConfiguration()");
        Toast.makeText(
                context,
                context.getResources().getString(R.string.wifi_install_error_message),
                Toast.LENGTH_SHORT)
            .show();
      }
    } else {
      Log.e(TAG, "Unknown error while calling WiFiManager.addNetwork()");
      Toast.makeText(
              context,
              context.getResources().getString(R.string.wifi_install_error_message),
              Toast.LENGTH_SHORT)
          .show();
    }
  }
Example #5
0
  /**
   * Update the network: either create a new network or modify an existing network
   *
   * @param config the new network configuration
   * @param disableOthers true if other networks must be disabled
   * @return network ID of the connected network.
   */
  private int updateNetwork(WifiConfiguration config, boolean disableOthers) {
    WifiConfiguration found = findNetworkInExistingConfig(config.SSID);
    wifiManager.disconnect();
    if (found == null) {
      statusView.setText(R.string.wifi_creating_network);
    } else {
      statusView.setText(R.string.wifi_modifying_network);
      Log.d(TAG, "Removing network " + found.networkId);
      wifiManager.removeNetwork(found.networkId);
      wifiManager.saveConfiguration();
    }
    networkId = wifiManager.addNetwork(config);
    Log.d(TAG, "Inserted/Modified network " + networkId);
    if (networkId < 0) {
      return FAILURE_NO_NETWORK_ID;
    }

    // Try to disable the current network and start a new one.
    if (!wifiManager.enableNetwork(networkId, disableOthers)) {
      networkId = FAILURE_NO_NETWORK_ID;
      return FAILURE_NO_NETWORK_ID;
    }
    errorCount = 0;
    wifiManager.reassociate();
    return networkId;
  }
Example #6
0
  /**
   * 提供一个外部接口,传入要连接的无线网
   *
   * @param SSID
   * @param Password
   * @param Type
   * @return
   */
  public boolean connect(String SSID, String Password, WifiCipherType Type) {
    if (!this.openWifi()) {
      return false;
    }
    // 开启wifi功能需要一段时间(我在手机上测试一般需要1-3秒左右),所以要等到wifi
    // 状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句
    while (mWifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
      try {
        // 为了避免程序一直while循环,让它睡个100毫秒在检测……
        Thread.currentThread();
        Thread.sleep(100);
      } catch (InterruptedException ie) {
      }
    }

    WifiConfiguration wifiConfig = this.createWifiInfo(SSID, Password, Type);
    //
    if (wifiConfig == null) {
      return false;
    }
    WifiConfiguration tempConfig = this.isExsits(SSID);
    if (tempConfig != null) {
      mWifiManager.removeNetwork(tempConfig.networkId);
    }
    int netID = mWifiManager.addNetwork(wifiConfig);
    // 是否去连接wifi
    boolean isConnect = mWifiManager.enableNetwork(netID, false);
    return isConnect;
  }
 // 指定配置好的网络进行连接
 public void connetionConfiguration(int index) {
   if (index > mWifiConfigurations.size()) {
     return;
   }
   // 连接配置好指定ID的网络
   mWifiManager.enableNetwork(mWifiConfigurations.get(index).networkId, true);
 }
Example #8
0
 // 指定配置好的网络进行连接
 public void connectConfiguration(int index) {
   // 索引大于配置好的网络索引返回
   if (index > mWifiConfiguration.size()) {
     return;
   }
   // 连接配置好的指定ID的网络
   mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, true);
 }
Example #9
0
 public void connectConfiguration(int index) {
   // ??????????ú???????????
   if (index > mWifiConfiguration.size()) {
     return;
   }
   // ???????ú?????ID??????
   mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, true);
 }
Example #10
0
 // ָ�����úõ������������
 public void connectConfiguration(int index) {
   // ����������úõ����������
   if (index > mWifiConfiguration.size()) {
     return;
   }
   // �������úõ�ָ��ID������
   mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, true);
 }
Example #11
0
	/**
	 * 添加到网络
	 * 
	 * @param wcg
	 */
	public boolean addNetwork(WifiConfiguration wcg) {
		if (wcg == null) {
			return false;
		}
		int wcgID = mWifiManager.addNetwork(wcg);
		boolean b = mWifiManager.enableNetwork(wcgID, true);
		mWifiManager.saveConfiguration();
		return b;
	}
 private static void reenableAllAps(final Context ctx) {
   final WifiManager wifiMgr = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
   final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks();
   if (configurations != null) {
     for (final WifiConfiguration config : configurations) {
       wifiMgr.enableNetwork(config.networkId, false);
     }
   }
 }
 private boolean connect(WifiConfiguration config) {
   mWifiManager.startScan();
   for (ScanResult result : mWifiManager.getScanResults()) {
     // Android4.2以降のダブルクォーテーションを除去
     LogUtils.i("config.SSID: " + getSsidName(config.SSID));
     LogUtils.i("result.SSID: " + getSsidName(result.SSID));
     if (getSsidName(config.SSID).equals(getSsidName(result.SSID))) {
       return mWifiManager.enableNetwork(config.networkId, true);
     }
   }
   return false;
 }
 public void connect(final Host host) {
   Log.d(TAG, "trying to connect to AP:" + host.access_point);
   final List<WifiConfiguration> hosts = mManager.getConfiguredNetworks();
   int networkId = -1;
   for (WifiConfiguration conf : hosts) {
     Log.d(TAG, "trying host:" + conf.SSID);
     if (conf.SSID.equalsIgnoreCase("\"" + host.access_point + "\"")) {
       networkId = conf.networkId;
       Log.d(TAG, "found hosts AP in Android with ID:" + networkId);
       break;
     }
   }
   mManager.enableNetwork(networkId, true);
 }
  public static void reconnect1() {
    try {
      List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
      for (WifiConfiguration i : list) {
        if (i.SSID.equals(FirstSettings_two.first_ssid)) {
          wifiManager.enableNetwork(i.networkId, true);
          wifiManager.reconnect();

          break;
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    ;
  }
Example #16
0
  // 链接并且保持wifi
  public boolean ConnectASaveWifi(int wifiId) {
    mWifiConfiguration = mWifiManager.getConfiguredNetworks(); // ??????ú?????????

    for (int i = 0; i < mWifiConfiguration.size(); i++) {
      WifiConfiguration wifi = mWifiConfiguration.get(i);
      if (wifi.networkId == wifiId) {
        while (!(mWifiManager.enableNetwork(wifiId, true))) {
          mWifiManager.updateNetwork(wifi);
          Log.i("ConnectWifi", String.valueOf(mWifiConfiguration.get(wifiId).status));
        }

        return true;
      }
    }
    return false;
  }
 public void reconnect5() {
   try {
     List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
     for (WifiConfiguration i : list) {
       if (i.SSID.equals(FirstSettings_two.first_ssid)) {
         wifiManager.enableNetwork(i.networkId, true);
         wifiManager.reconnect();
         File_Video downloadFile_video = new File_Video();
         downloadFile_video.execute(BroadcastNewSms.filepath);
         break;
       }
     }
   } catch (Exception e) {
     Toast.makeText(getApplicationContext(), e.getMessage().toString(), Toast.LENGTH_LONG).show();
   }
   ;
 }
  public boolean connectToXfinityWifiNetwork(String bssid) {

    appendDebug("Attempting to connect to XfinityWifi: " + bssid);
    WifiConfiguration wifiConfig = new WifiConfiguration();
    wifiConfig.BSSID = bssid;
    wifiConfig.priority = 1;
    wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
    wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
    wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    wifiConfig.status = WifiConfiguration.Status.ENABLED;

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    int netId = wifi.addNetwork(wifiConfig);

    if (netId == -1) return false;
    wifi.enableNetwork(netId, true);

    // wait for connect signal
    long timeout_length = 15000; // ms
    boolean successful_connection = false;
    try {
      // SHITTY: loop through with sleep for finish
      for (int i = 0; i < timeout_length / 500; i++) {

        NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (ni.isConnected()) {
          WifiInfo wi = wifi.getConnectionInfo();

          if (wi.getBSSID().equals(bssid)) {
            successful_connection = true;
            break;
          }
        }

        Thread.sleep(500);
      }
    } catch (InterruptedException ie) {
      // something bad happened
      // don't do anythign though
    }

    return successful_connection;
  }
  /**
   * Enable the scan access point which has no security. This may result in the asynchronous
   * delivery of state change events. Applications should register the
   * 'SUPPLICANT_STATE_CHANGED_ACTION' and 'NETWORK_STATE_CHANGED_ACTION' receiver to receive the
   * state change events.
   *
   * @param One of the access point which want to link.
   * @return Return true if the operation succeed, false otherwise.
   */
  public boolean enableNetworkLink(ScanResult result) {
    if (WifiConst.DummyMode) {
      return false;
    }

    int networkId = -1;
    if (result == null) {
      return false;
    }

    if (isConfigured(result)) {
      if (localLOGV)
        NetLog.d(
            TAG, "[WifiAvailableAp][EnableNetworkLink]: " + result.SSID + " has been configured.");
      networkId = getNetworkId(result);
    } else {
      if (localLOGV)
        NetLog.d(
            TAG,
            "[WifiAvailableAp][EnableNetworkLink]: " + result.SSID + " has not been configured.");
      WifiConfiguration config = new WifiConfiguration();

      config.SSID = WifiUtil.convertToQuotedString(result.SSID);
      config.allowedKeyManagement.set(KeyMgmt.NONE);
      config.status = WifiConfiguration.Status.ENABLED;
      networkId = mWifiManager.addNetwork(config);
      mWifiManager.updateNetwork(config);
    }

    if (networkId == -1) {
      return false;
    }

    if (mWifiManager.enableNetwork(networkId, true)) {
      mWifiManager.reconnect();

      if (localLOGV)
        NetLog.d(TAG, "[WifiAvailableAp][EnableNetworkLink]: enable network link success.");
      return true;
    }

    return false;
  }
Example #20
0
  void Connect() {
    Log.i("starwisp", "Attemping connect to " + SSID);

    List<WifiConfiguration> list = wifi.getConfiguredNetworks();

    Boolean found = false;

    for (WifiConfiguration i : list) {
      if (i.SSID != null && i.SSID.equals("\"" + SSID + "\"")) {
        found = true;
        Log.i("starwisp", "Connecting (state=connected)");
        state = State.CONNECTED;
        wifi.disconnect();
        wifi.enableNetwork(i.networkId, true);
        wifi.reconnect();
        Log.i("starwisp", "Connected");
        try {
          Thread.sleep(2000);
          Log.i("starwisp", "trying post-connection callback");
          m_Builder.DialogCallback(m_Context, m_Context.m_Name, m_CallbackName, "\"Connected\"");
        } catch (Exception e) {
          Log.i("starwisp", e.toString());
          e.printStackTrace();
        }

        break;
      }
    }

    if (!found) {
      Log.i("starwisp", "adding wifi config");
      WifiConfiguration conf = new WifiConfiguration();
      conf.SSID = "\"" + SSID + "\"";

      // conf.wepKeys[0] = "\"" + networkPass + "\"";
      // conf.wepTxKeyIndex = 0;
      // conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
      // conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);

      conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
      wifi.addNetwork(conf);
    }
  }
Example #21
0
	/**
	 * Function: 提供一个外部接口,传入要连接的无线网 <br>
	 * 
	 * @author ZYT DateTime 2014-5-13 下午11:46:54<br>
	 * @param SSID
	 *            SSID
	 * @param Password
	 * @param Type
	 * <br>
	 *            没密码:{@linkplain WifiCipherType#WIFICIPHER_NOPASS}<br>
	 *            WEP加密: {@linkplain WifiCipherType#WIFICIPHER_WEP}<br>
	 *            WPA加密: {@linkplain WifiCipherType#WIFICIPHER_WPA}
	 * @return true:连接成功;false:连接失败<br>
	 */
	public boolean connect(String SSID, String Password, WifiCipherType Type) {
		if (!this.openWifi()) {
			return false;
		}
		// 开启wifi功能需要一段时间(我在手机上测试一般需要1-3秒左右),所以要等到wifi
		// 状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句
		while (mWifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
			try {
				// 为了避免程序一直while循环,让它睡个100毫秒在检测……
				Thread.currentThread();
				Thread.sleep(100);
			} catch (InterruptedException ie) {
			}
		}

		System.out.println("WifiAdmin#connect==连接结束");

		WifiConfiguration wifiConfig = createWifiInfo(SSID, Password, Type);
		//
		if (wifiConfig == null) {
			return false;
		}

		WifiConfiguration tempConfig = this.isExsits(SSID);

		int tempId = wifiConfig.networkId;
		if (tempConfig != null) {
			tempId = tempConfig.networkId;
			mWifiManager.removeNetwork(tempConfig.networkId);
		}

		int netID = mWifiManager.addNetwork(wifiConfig);

		// 断开连接
		mWifiManager.disconnect();
		// 重新连接
		// netID = wifiConfig.networkId;
		// 设置为true,使其他的连接断开
		boolean bRet = mWifiManager.enableNetwork(netID, true);
		mWifiManager.reconnect();
		return bRet;
	}
 /**
  * Update the network: either create a new network or modify an existing network
  *
  * @param config the new network configuration
  * @return network ID of the connected network.
  */
 private static void updateNetwork(WifiManager wifiManager, WifiConfiguration config) {
   Integer foundNetworkID = findNetworkInExistingConfig(wifiManager, config.SSID);
   if (foundNetworkID != null) {
     Log.i(TAG, "Removing old configuration for network " + config.SSID);
     wifiManager.removeNetwork(foundNetworkID);
     wifiManager.saveConfiguration();
   }
   int networkId = wifiManager.addNetwork(config);
   if (networkId >= 0) {
     // Try to disable the current network and start a new one.
     if (wifiManager.enableNetwork(networkId, true)) {
       Log.i(TAG, "Associating to network " + config.SSID);
       wifiManager.saveConfiguration();
     } else {
       Log.w(TAG, "Failed to enable network " + config.SSID);
     }
   } else {
     Log.w(TAG, "Unable to add network " + config.SSID);
   }
 }
Example #23
0
	public boolean connectSpecificAP(ScanResult scan) {
		List<WifiConfiguration> list = mWifiManager.getConfiguredNetworks();
		boolean networkInSupplicant = false;
		boolean connectResult = false;
		// 重新连接指定AP
		mWifiManager.disconnect();
		for (WifiConfiguration w : list) {
			// 将指定AP 名字转化
			// String str = convertToQuotedString(info.ssid);
			if (w.BSSID != null && w.BSSID.equals(scan.BSSID)) {
				connectResult = mWifiManager.enableNetwork(w.networkId, true);
				// mWifiManager.saveConfiguration();
				networkInSupplicant = true;
				break;
			}
		}
		if (!networkInSupplicant) {
			WifiConfiguration config = CreateWifiInfo(scan, "");
			connectResult = addNetwork(config);
		}

		return connectResult;
	}
Example #24
0
 // ���һ�����粢����
 public Boolean addNetwork(WifiConfiguration wcg) {
   int wcgID = mWifiManager.addNetwork(wcg);
   return mWifiManager.enableNetwork(wcgID, true);
 }
Example #25
0
 // 添加一个网络并连接
 public void addNetwork(WifiConfiguration wcg) {
   int wcgID = mWifiManager.addNetwork(wcg);
   boolean b = mWifiManager.enableNetwork(wcgID, true);
   System.out.println("a--" + wcgID);
   System.out.println("b--" + b);
 }
Example #26
0
    @Override
    protected Action doInBackground(Void... arg) {
      wakeLock.acquire();

      try {
        ChipsetDetection detection = ChipsetDetection.getDetection();
        while (true) {
          boolean result = false;
          boolean fatal = currentAction.fatal;
          try {
            Log.v("BatPhone", "Performing action " + currentAction);

            switch (currentAction) {
              case Unpacking:
                app.installFilesIfRequired();
                result = true;
                break;

              case AdhocWPA:
                if (false) {
                  // Get wifi manager
                  WifiManager wm =
                      (WifiManager)
                          ServalBatPhoneApplication.context.getSystemService(Context.WIFI_SERVICE);

                  // enable wifi
                  wm.setWifiEnabled(true);
                  WifiConfiguration wc = new WifiConfiguration();
                  wc.SSID = "*supplicant-test";
                  int res = wm.addNetwork(wc);
                  Log.d("BatPhone", "add Network returned " + res);
                  boolean b = wm.enableNetwork(res, true);
                  Log.d("WifiPreference", "enableNetwork returned " + b);
                }
                break;

              case RootCheck:
                result = ServalBatPhoneApplication.context.coretask.hasRootPermission();
                break;

              case Supported:
                // Start out by only looking for non-experimental
                // chipsets
                detection.identifyChipset();
                result = detection.detected_chipsets.size() > 0;
                break;

              case Experimental:
                if (!results[Action.Supported.ordinal()]) {
                  detection.inventSupport();
                  // this will not select a chipset
                  detection.detect(true);
                  result = detection.detected_chipsets.size() > 0;
                }
                break;

              case CheckSupport:
                result = testSupport();
                break;

              case Finished:
                break;
            }

          } catch (Exception e) {
            result = false;
            Log.e("BatPhone", e.toString(), e);
            app.displayToastMessage(e.getMessage());
            fatal = true;
          }

          results[currentAction.ordinal()] = result;
          Log.v("BatPhone", "Result " + result);

          if (fatal && !result) {
            fatalError = true;
            return currentAction;
          }

          if (currentAction == Action.Finished) {
            ServalBatPhoneApplication.wifiSetup = true;
            return currentAction;
          }

          this.publishProgress(currentAction);
          currentAction = Action.values()[currentAction.ordinal() + 1];
        }
      } finally {
        wakeLock.release();
        dismissTryExperimentalChipsetDialog();
      }
    }
  public void connectToAP(String ssid, String passkey, Context ctx) {
    //	    Log.i(TAG, "* connectToAP");

    WifiConfiguration wifiConfiguration = new WifiConfiguration();
    WifiManager wifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
    String networkSSID = ssid;
    String networkPass = passkey;

    //	    Log.d(TAG, "# password " + networkPass);
    if (results != null && results.size() > 0) {
      for (ScanResult result : results) {
        if (result.SSID.equals(networkSSID)) {

          String securityMode = getScanResultSecurity(result);

          if (securityMode.equalsIgnoreCase("OPEN")) {

            wifiConfiguration.SSID = "\"" + networkSSID + "\"";
            wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            int res = wifiManager.addNetwork(wifiConfiguration);
            //	                Log.d(TAG, "# add Network returned " + res);

            wifiManager.enableNetwork(res, true);
            //	                Log.d(TAG, "# enableNetwork returned " + b);

            wifiManager.setWifiEnabled(true);

          } else if (securityMode.equalsIgnoreCase("WEP")) {

            wifiConfiguration.SSID = "\"" + networkSSID + "\"";
            wifiConfiguration.wepKeys[0] = "\"" + networkPass + "\"";
            wifiConfiguration.wepTxKeyIndex = 0;
            wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            int res = wifiManager.addNetwork(wifiConfiguration);
            //	                Log.d(TAG, "### 1 ### add Network returned " + res);

            wifiManager.enableNetwork(res, true);
            //	                Log.d(TAG, "# enableNetwork returned " + b);

            wifiManager.setWifiEnabled(true);
          }

          wifiConfiguration.SSID = "\"" + networkSSID + "\"";
          wifiConfiguration.preSharedKey = "\"" + networkPass + "\"";
          wifiConfiguration.hiddenSSID = true;
          wifiConfiguration.status = WifiConfiguration.Status.ENABLED;
          wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
          wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
          wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
          wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
          wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
          wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
          wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA);

          int res = wifiManager.addNetwork(wifiConfiguration);

          wifiManager.enableNetwork(res, true);

          boolean changeHappen = wifiManager.saveConfiguration();

          wifiManager.setWifiEnabled(true);
          if (res != -1 && changeHappen) {

            if (!checkNetwrk())
              Toast.makeText(
                      ctx,
                      "wifi password is set but no internet access. Restart the router",
                      Toast.LENGTH_LONG)
                  .show();
            else Toast.makeText(ctx, "wifi is connected", Toast.LENGTH_LONG).show();
            try {
              Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            Intent i = new Intent(ctx, InternetConnectionSetting.class);
            startActivity(i);
            finish();
          }
        }
      }
    } else {
      getWifiList();
    }
  }
  /**
   * Enable the scan access point which has security. This may result in the asynchronous delivery
   * of state change events. Applications should register the 'SUPPLICANT_STATE_CHANGED_ACTION' and
   * 'NETWORK_STATE_CHANGED_ACTION' receiver to receive the state change events.
   *
   * @param One of the access point which want to link.
   * @return Return true if the operation succeed, false otherwise.
   */
  public boolean enableNetworkLink(ScanResult result, String sectretKey) {
    if (WifiConst.DummyMode) {
      return false;
    }

    int networkId = -1;
    int keyLength = sectretKey.length();
    WifiConfiguration config = new WifiConfiguration();
    if (localLOGV)
      NetLog.d(TAG, "[WifiAvailableAp][EnableNetworkLink]: Enable Access Point with Password.");
    if (result == null || sectretKey == null) {
      return false;
    }

    WifiUtil.clearConfiguration(config);
    config.status = WifiConfiguration.Status.ENABLED;

    config.SSID = WifiUtil.convertToQuotedString(result.SSID);

    int encrypt = WifiUtil.getEncrypt(result);

    if (encrypt == WifiConst.W_ENCRYPT_WEP) {
      if (localLOGV) NetLog.d(TAG, "[WifiAvailableAp][EnableNetworkLink]: WEP encrypt.");
      if ((keyLength == 5 || keyLength == 10 || keyLength == 13 || keyLength == 26)
          && sectretKey.matches("[0-9A-Fa-f]*")) {
        config.wepKeys[0] = sectretKey;
      } else {
        config.wepKeys[0] = '"' + sectretKey + '"';
      }
    } else {
      if (localLOGV) NetLog.d(TAG, "[WifiAvailableAp][EnableNetworkLink]: other encrypt.");
      if (sectretKey.matches("[0-9A-Fa-f]{64}")) {
        config.preSharedKey = sectretKey;
      } else {
        config.preSharedKey = "\"" + sectretKey + "\"";
      }
    }

    int ConfirmType = WifiUtil.getConfirmType(result);
    switch (ConfirmType) {
      case WifiConst.W_CONFIRM_OPEN:
        if (localLOGV) NetLog.d(TAG, "[WifiAvailableAp][EnableNetworkLink]: W_CONFIRM_OPEN");
        config.allowedKeyManagement.set(KeyMgmt.NONE);
        config.allowedAuthAlgorithms.clear();
        config.allowedPairwiseCiphers.set(PairwiseCipher.NONE);
        config.allowedGroupCiphers.clear();
        config.allowedProtocols.clear();
        break;

      case WifiConst.W_CONFIRM_WEP:
        if (localLOGV) NetLog.d(TAG, "[WifiAvailableAp][EnableNetworkLink]: W_CONFIRM_WEP");
        config.allowedKeyManagement.set(KeyMgmt.NONE);
        config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
        config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
        config.allowedPairwiseCiphers.set(PairwiseCipher.NONE);

        if (keyLength == 5 || keyLength == 10) {
          config.allowedGroupCiphers.set(GroupCipher.WEP40);
        } else {
          config.allowedGroupCiphers.set(GroupCipher.WEP104);
        }

        config.allowedProtocols.clear();
        break;

      case WifiConst.W_CONFIRM_WPA_PSK:
        if (localLOGV) NetLog.d(TAG, "[WifiAvailableAp][EnableNetworkLink]: W_CONFIRM_WPA_PSK");
        config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
        config.allowedProtocols.set(Protocol.WPA);
        config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
        break;

      case WifiConst.W_CONFIRM_WPA2_PSK:
        if (localLOGV) NetLog.d(TAG, "[WifiAvailableAp][EnableNetworkLink]: W_CONFIRM_WPA2_PSK");
        config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
        config.allowedProtocols.set(Protocol.RSN);
        config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
        break;

      case WifiConst.W_CONFIRM_PSK_AUTO:
        if (localLOGV) NetLog.d(TAG, "[WifiAvailableAp][EnableNetworkLink]: W_CONFIRM_PSK_AUTO");
        config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
        config.allowedProtocols.set(Protocol.RSN);
        config.allowedProtocols.set(Protocol.WPA);
        config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
        break;

      case WifiConst.W_CONFIRM_WPA_EAP:
        if (localLOGV) NetLog.d(TAG, "[WifiAvailableAp][EnableNetworkLink]: W_CONFIRM_WPA_EAP");
        config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
        config.allowedProtocols.set(Protocol.WPA);
        config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
        break;

      case WifiConst.W_CONFIRM_WPA2_EAP:
        if (localLOGV) NetLog.d(TAG, "[WifiAvailableAp][EnableNetworkLink]: W_CONFIRM_WPA2_EAP");
        config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
        config.allowedProtocols.set(Protocol.RSN);
        config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
        break;

      case WifiConst.W_CONFIRM_EAP_AUTO:
        if (localLOGV) NetLog.d(TAG, "[WifiAvailableAp][EnableNetworkLink]: W_CONFIRM_EAP_AUTO");
        config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
        config.allowedProtocols.set(Protocol.RSN);
        config.allowedProtocols.set(Protocol.WPA);
        config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
        break;

      default:
        break;
    }

    switch (encrypt) {
      case WifiConst.W_ENCRYPT_WEP:
        break;

      case WifiConst.W_ENCRYPT_TKIP:
        if (localLOGV) NetLog.d(TAG, "[WifiAvailableAp][EnableNetworkLink]: W_ENCRYPT_TKIP");
        config.allowedGroupCiphers.set(GroupCipher.TKIP);
        config.allowedPairwiseCiphers.set(PairwiseCipher.TKIP);
        break;

      case WifiConst.W_ENCRYPT_AES:
        if (localLOGV) NetLog.d(TAG, "[WifiAvailableAp][EnableNetworkLink]: W_ENCRYPT_AES");
        config.allowedGroupCiphers.set(GroupCipher.CCMP);
        config.allowedPairwiseCiphers.set(PairwiseCipher.CCMP);
        break;

      case WifiConst.W_ENCRYPT_TKIP_AES:
        if (localLOGV) NetLog.d(TAG, "[WifiAvailableAp][EnableNetworkLink]: W_ENCRYPT_TKIP_AES");
        config.allowedGroupCiphers.set(GroupCipher.TKIP);
        config.allowedGroupCiphers.set(GroupCipher.CCMP);
        config.allowedPairwiseCiphers.set(PairwiseCipher.TKIP);
        config.allowedPairwiseCiphers.set(PairwiseCipher.CCMP);
        break;

      default:
        if (localLOGV) NetLog.d(TAG, "[WifiAvailableAp][EnableNetworkLink]: W_ENCRYPT default.");
        break;
    }

    networkId = mWifiManager.addNetwork(config);
    if (localLOGV)
      NetLog.d(TAG, "[WifiAvailableAp][EnableNetworkLink]: 398  networkId -> " + networkId);
    mWifiManager.updateNetwork(config);

    if (networkId == -1) {
      return false;
    }

    if (mWifiManager.enableNetwork(networkId, true)) {
      if (localLOGV)
        NetLog.d(TAG, "[WifiAvailableAp][EnableNetworkLink]: Enable network link SUCCESS.");

      mWifiManager.reconnect();

      return true;
    }

    return false;
  }
Example #29
0
	// 添加一个网络并连接
	public void addNetWork(WifiConfiguration configuration) {
		int wcgId = mWifiManager.addNetwork(configuration);
		mWifiManager.enableNetwork(wcgId, true);
	}
 public static void connectToWifi(WifiManager wifiManager, int networkId) {
   wifiManager.disconnect();
   wifiManager.enableNetwork(networkId, true);
   wifiManager.reconnect();
 }