Android 關於wifi管理的代碼

開啟和關閉wifi的代碼

1、需要申請的權限

  android.permission.ACCESS_WIFI_STATE

  android.permission.CHANGE_WIFI_STATE

  android.permission.WAKE_LOCK

2、獲取WifiManager

  wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);

3、開啟、關閉wifi

  if (wifiManager.isWifiEnabled()) {

  wifiManager.setWifiEnabled(false);

  } else {

  wifiManager.setWifiEnabled(true);

  }

 

Android設置wifi

1.new 一個wificonfiguration對象。

2.設置這個對象的一些屬性。

[java]  

<span style="font-size:18px">WifiConfiguration wc = new WifiConfiguration();  

wc.SSID = "\""+sr.SSID+"\"";      //<span style="color: rgb(255, 0, 0); ">這個地方一定要註意瞭。旁邊的“是不能夠省略的。密碼的地方也一樣。</span>  

wc.preSharedKey = "\""+etPassword.getText().toString()+"\"";      //該熱點的密碼  

wc.hiddenSSID = true;  

wc.status = WifiConfiguration.Status.ENABLED;  

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

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

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

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

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

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

wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);</span>  

3.判斷wifi是否加密:

[java] 

<span style="font-size:18px">    public static int getSecurity(ScanResult result) {  

        if (result.capabilities.contains("WEP")) {  

            return 1;  

        } else if (result.capabilities.contains("PSK")) {  

            return 2;  

        } else if (result.capabilities.contains("EAP")) {  

            return 3;  

        }  

        return 0;  

    }  

    </span>  

4.連接未加密wifi連接:

[java]  

<span style="font-size:18px"><pre name="code" class="java">WifiConfiguration config = new WifiConfiguration();  

config.SSID = "\"" + sr.SSID + "\"";  

config.allowedKeyManagement.set(KeyMgmt.NONE);  

int networkId = wifiManager.addNetwork(config);  

if(networkId != -1){  

    wifiManager.enableNetwork(networkId, false);  

    wifiManager.saveConfiguration();  

}</pre><p></p>  

<pre></pre>  

<p></p>  

</span>  

 

 

 

 

發佈留言