wifi热点创建和自动连接

简介:

1.wifi热点的创建

  /**
  * 创建wifi热点
  * @param ssid 热点信息
  * @param passwd  密码
  * @author wanghongbin
  */
 public void startWifiAp(Context context, String ssid, String passwd) {
 //关闭wifi
 closeWifi();
 //关闭热点
 closeWifiAp();
 //激活热点
 invokeWifiAp(ssid, passwd);
 }

       /**
  * 激活wifi热点
  * @param ssid
  * @param passwd
  * @author wanghongbin
  */
 private void invokeWifiAp(String ssid, String passwd) {
 try {
 Method method1 = mWifiManager.getClass().getMethod("setWifiApEnabled",
 WifiConfiguration.class, boolean.class);
 WifiConfiguration netConfig = new WifiConfiguration();

 netConfig.SSID = ssid;
 netConfig.preSharedKey =   passwd ;
 //启动热点
 boolean isSuccess = (Boolean)method1.invoke(mWifiManager, netConfig, true);
 Log.i(TAG, "whb end startWifiAp isSuccess="+isSuccess);
 } catch (IllegalArgumentException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 Log.i(TAG, "whb end startWifiAp IllegalArgumentException");
 } catch (IllegalAcces***ception e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 Log.i(TAG, "whb end startWifiAp IllegalAcces***ception");
 } catch (InvocationTargetException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
// onNotifyWifiNotSurpport();
 Log.i(TAG, "whb end startWifiAp onNotifyWifiNotSurpport");
 } catch (SecurityException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 Log.i(TAG, "whb end startWifiAp SecurityException");
 } catch (NoSuchMethodException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
  onNotifyWifiNotSurpport();
  Log.i(TAG, "whb end startWifiAp NoSuchMethodException");
 }
 }

 // 关闭WIFI
 public void closeWifi() {
 if (mWifiManager.isWifiEnabled()) {
 mWifiManager.setWifiEnabled(false);
 }
 } 

     //作热点之前先关闭wifi热点服务
 public  void closeWifiAp( ) {
 if (isWifiApEnabled()) {
 try {
 Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
 method.setAccessible(true);

 WifiConfiguration config = (WifiConfiguration) method.invoke(mWifiManager);

 Method method2 = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
 method2.invoke(mWifiManager, config, false);
 } catch (NoSuchMethodException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (IllegalArgumentException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (IllegalAcces***ception e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (InvocationTargetException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 }
 }

2.连接热点

  /**
  * 添加一个网络节点并连接
  * @param ssid   wifi节点名称
  * @param passwd  密码
  * @param type  : TYPE_WEP TYPE_WPA
  */
 public void addNetwork(Context context, String ssid, String passwd, int type) {
 closeWifiAp();
 openWifi();

 mConfig = createWifiInfo(ssid, passwd, type);
 SSID = ssid;
 connectToWifiWithConfiguration(mConfig);
 }

     public static final int WAIT_FOR_SCAN_RESULT = 10 * 1000; //10 seconds
     public static final int WIFI_SCAN_TIMEOUT = 20 * 1000;
     /**
      * 连接指定热点
      * @param config
      * @return true : 调用函数成功,具体网络状态还得检测
      * @author wanghongbin  这个函数害死人阿,网上看了半天也没人说,最后是看的源代码里的WifiConnectionTest.java才明白需要等待,步步等待,步步惊心
      */
 public boolean connectToWifiWithConfiguration(WifiConfiguration config) {
         String ssid = config.SSID;
         config.SSID = "\""+ssid+"\"";

         //If Wifi is not enabled, enable it
         if (!mWifiManager.isWifiEnabled()) {
             Log.v(TAG, "Wifi is not enabled, enable it");
             mWifiManager.setWifiEnabled(true);
         }

         List<ScanResult> netList = mWifiManager.getScanResults();
         if (netList == null) {
             Log.v(TAG, "scan results are null");
             // if no scan results are available, start active scan
             mWifiManager.startScan();
             boolean mScanResultIsAvailable = false;
             long startTime = System.currentTimeMillis();
             while (!mScanResultIsAvailable) {
                 if ((System.currentTimeMillis() - startTime) > WIFI_SCAN_TIMEOUT) {
                     return false;
                 }
                 // wait for the scan results to be available
                 synchronized (this) {
                     // wait for the scan result to be available
                     try {
                         this.wait(WAIT_FOR_SCAN_RESULT);
                     } catch (InterruptedException e) {
                         e.printStackTrace();
                     }
                     if ((mWifiManager.getScanResults() == null) ||
                             (mWifiManager.getScanResults().size() <= 0)) {
                         continue;
                     }
                     mScanResultIsAvailable = true;
                 }
             }
         }

         netList = mWifiManager.getScanResults();

         for (int i = 0; i < netList.size(); i++) {
             ScanResult sr= netList.get(i);
             if (sr.SSID.equals(ssid)) {
                 Log.v(TAG, "found " + ssid + " in the scan result list");
                 int networkId = mWifiManager.addNetwork(config);
                 // Connect to network by disabling others.
                 mWifiManager.enableNetwork(networkId, true);
                 mWifiManager.saveConfiguration();
                 mWifiManager.reconnect();
                 break;
            }
         }

         List<WifiConfiguration> netConfList = mWifiManager.getConfiguredNetworks();
         if (netConfList.size() <= 0) {
             Log.v(TAG, ssid + " is not available");
             return false;
         }
         return true;
     }

 public static final int TYPE_NO_PASSWD = 0x11;
 public static final int TYPE_WEP = 0x12;
 public static final int TYPE_WPA = 0x13;
     /**
  * 连接信息生成配置对象
  * @param SSID
  * @param password
  * @param type
  * @return
  * @author wanghongbin
  */
 public WifiConfiguration createWifiInfo(String SSID, String password, int type) {
 
 Log.v(TAG, "whb SSID =" + SSID + "## Password =" + password + "## Type = " + type);
 
       WifiConfiguration config = new WifiConfiguration();

        config.SSID = SSID;       

        clearAll(SSID);





        // 分为三种情况:1没有密码2用wep加密3用wpa加密

        if (type == TYPE_NO_PASSWD) {// WIFICIPHER_NOPASS

            config.hiddenSSID = false;

            config.status =  WifiConfiguration.Status.ENABLED;

            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

            config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);

            config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);

            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);

            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);

            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);

            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);

            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);

            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);

            config.preSharedKey = null;

        } else if (type == TYPE_WEP) { // WIFICIPHER_WEP

            config.hiddenSSID = true;

            config.wepKeys[0] = "\"" + password + "\"";

            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);

            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);

            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);

            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);

            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);

            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

            config.wepTxKeyIndex = 0;

        } else if (type == TYPE_WPA) { // WIFICIPHER_WPA

            config.preSharedKey = "\"" + password + "\"";

            config.hiddenSSID = false;

            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);

            config.priority = 10000;

            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);

            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);

            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);

            config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);

            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);

            config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);

            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);

            config.status = WifiConfiguration.Status.ENABLED;

        }

	


  
 return config;
 }

3.很多之前已经连接上的WIFI,配置信息会自动保存,当你关闭---->打开WIFI时就会自动连接,但有时我们并不希望这样处理, 解决方法为在打开WIFI之前将以前所保存的信息清除,代码为
if(isWifiConnect()){
    WifiInfo info = mWifiManager.getConnectionInfo();
    mWifiManager.removeNetwork(info.getNetworkId());
    mWifiManager.saveConfiguration();
   }
  或者
/**
  * 移除所有同名节点
  * @param SSID
  */
 private void clearAll(String SSID) {
 List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
 //按照networkId从大到小排序
 Collections.sort(existingConfigs, new ComparatorConfig());
 for (WifiConfiguration existingConfig : existingConfigs) {
 LogHelper.i(TAG,"existingConfig.SSID="+existingConfig.SSID+",netID = "+ existingConfig.networkId);
 if (existingConfig.SSID.equals("\""+SSID+"\"") /*&& existingConfig.preSharedKey.equals("\"" + password + "\"")*/) {
 mWifiManager.disableNetwork(existingConfig.networkId);
 mWifiManager.removeNetwork(existingConfig.networkId);
 }
 }
 mWifiManager.saveConfiguration();
 }



相关文章
|
3月前
|
存储 网络安全 Python
WiFi连接树莓派【2月更文挑战第2天】
要通过WiFi连接树莓派并显示其摄像头视频信息,您需要按照以下步骤操作: 1. 确保您的电脑和树莓派已连接到同一个WiFi网络。 2. 安装Python和必要的库:在您的电脑上安装Python 3.6或更高版本,并安装pip(Python包管理器)。然后,通过pip安装以下库: 【2月更文挑战第2天】
25 1
|
4月前
|
定位技术 Android开发
uniapp获取wifi连接状态
uniapp获取wifi连接状态
132 0
|
8月前
|
安全 数据安全/隐私保护 网络架构
如何查看电脑所有连接过的wifi密码?
如何查看电脑所有连接过的wifi密码?
290 0
|
6天前
|
Android开发
android连接指定wifi
android连接指定wifi
15 0
|
6天前
|
Java Android开发
Android 9在连接以太网情况下 还能连接WiFi
Android 9在连接以太网情况下 还能连接WiFi
9 0
|
2月前
|
前端开发 安全 数据安全/隐私保护
WPA_CLI 的介绍:介绍如何使用wpa_cli连接WiFi的方法
WPA_CLI 的介绍:介绍如何使用wpa_cli连接WiFi的方法
66 2
|
6月前
|
安全 数据安全/隐私保护
windows10 查看已连接wifi的密码
windows10 查看已连接wifi的密码
148 0
|
5月前
|
Android开发 网络架构
【Android App】检查手机连接WiFi信息以及扫描周围WiFi的讲解及实战(附源码和演示 超详细必看)
【Android App】检查手机连接WiFi信息以及扫描周围WiFi的讲解及实战(附源码和演示 超详细必看)
248 1
|
8月前
|
Linux 数据安全/隐私保护
如何在 Linux 中使用 nmcli 连接 WiFi?
如何在 Linux 中使用 nmcli 连接 WiFi?
155 0
|
8月前
|
Android开发
Android获取已连接wifi的热点信息(上位机开发学习之多个界面切换编程)
Android获取已连接wifi的热点信息(上位机开发学习之多个界面切换编程)
191 0