【移動開發】Android中WIFI開發總結(一)

WIFI就是一種無線聯網技術,常見的是使用無線路由器。那麼在這個無線路由器的信號覆蓋的范圍內都可以采用WIFI連接的方式進行聯網。如果無線路由器連接瞭一個ADSL線路或其他的聯網線路,則又被稱為“熱點”。

在Android中對Wifi操作,android本身提供瞭一些有用的包,在android.net.wifi包下面,主要包括以下幾個類和接口:

1.ScanResult

主要用來描述已經檢測出的接入點,包括接入點的地址,接入點的名稱,身份認證,頻率,信號強度等信息。其實就是通過wifi 硬件的掃描來獲取一些周邊的wifi 熱點的信息。

2.WifiConfiguration

Wifi網絡的配置,包括安全設置等,在我們連通一個wifi 接入點的時候,需要獲取到的一些信息。主要包含四個屬性:

BSSID:

BSS是一種特殊的Ad-hoc LAN(一種支持點對點訪問的無線網絡應用模式)的應用,一個無線網絡至少由一個連接到有線網絡的AP和若幹無線工作站組成,這種配置稱為一個基本服務裝置。一群計算機設定相同的 BSS名稱,即可自成一個group,而此BSS名稱,即所謂BSSID。通常,手機WLAN中,bssid其實就是無線路由的MAC地址。

networkid:網絡ID。

PreSharedKey:無線網絡的安全認證模式。

SSID:SSID(Service Set Identif)用於標識無線局域網,SSID不同的無線網絡是無法進行互訪的。

3.WifiInfo

wifi無線連接的描述,包括(接入點,網絡連接狀態,隱藏的接入點,IP地址,連接速度,MAC地址,網絡ID,信號強度等信息)。這裡簡單介紹一下WifiManager中常用的方法:

getSSID() 獲得SSID(熱點名稱)

getBSSID()

獲取BSSID
getDetailedStateOf() 獲取客戶端的連通性
getHiddenSSID() 獲得SSID 是否被隱藏
getIpAddress() 獲取IP 地址
getLinkSpeed() 獲得連接的速度
getMacAddress() 獲得Mac 地址
getRssi() 獲得802.11n 網絡的信號

4.WifiManager

wifi連接統一管理類,獲取WIFI網卡的狀態(WIFI網卡的狀態是由一系列的整形常量來表示的)

WIFI_STATE_DISABLING = 0 WIFI網卡正在關閉
WIFI_STATE_DISABLED = 1 WIFI網卡不可用
WIFI_STATE_ENABLING = 2 WIFI網正在打開(WIFI啟動需要一段時間)
WIFI_STATE_ENABLED = 3 WIFI網卡可用
WIFI_STATE_UNKNOWN = 4 未知網卡狀態
WIFI_AP_STATE_DISABLING = 10 WIFI熱點正在關閉
WIFI_AP_STATE_DISABLED = 11 WIFI熱點不可用
WIFI_AP_STATE_ENABLING = 12 WIFI熱點正在打開
WIFI_AP_STATE_ENABLED = 13 WIFI熱點可用

5. 在AndroidManifest.xml進行對WIFI操作的權限設置

<!-- 以下是使用wifi訪問網絡所需的權限 -->
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"></uses-permission>
  <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>

下面是匯總的一個wifi管理工具類,我完善瞭一下,並加上瞭詳細的註解,很實用的!

WifiAdmin類: (wifi管理工具類)

package com.zhf.wifidemo.wifi.utils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
/**
 * WIFI管理類
 * @author ZHF
 *
 */
public class WifiAdmin {
    private static  WifiAdmin wifiAdmin = null;
                                                                                                                                                           
    private List<WifiConfiguration> mWifiConfiguration; //無線網絡配置信息類集合(網絡連接列表)
    private List<ScanResult> mWifiList; //檢測到接入點信息類 集合
                                                                                                                                                           
    //描述任何Wifi連接狀態
    private WifiInfo mWifiInfo;
                                                                                                                                                           
    WifiManager.WifiLock mWifilock; //能夠阻止wifi進入睡眠狀態,使wifi一直處於活躍狀態
    public WifiManager mWifiManager;
                                                                                                                                                           
    /**
     * 獲取該類的實例(懶漢)
     * @param context
     * @return
     */
    public static WifiAdmin getInstance(Context context) {
        if(wifiAdmin == null) {
            wifiAdmin = new WifiAdmin(context);
        }
        return wifiAdmin;
    }
    private WifiAdmin(Context context) {
        //獲取系統Wifi服務   WIFI_SERVICE
        this.mWifiManager = (WifiManager) context.getSystemService("wifi");
        //獲取連接信息
        this.mWifiInfo = this.mWifiManager.getConnectionInfo();
    }
                                                                                                                                                           
    /**
     * 是否存在網絡信息
     * @param str  熱點名稱
     * @return
     */
    private WifiConfiguration isExsits(String str) {
        Iterator localIterator = this.mWifiManager.getConfiguredNetworks().iterator();
        WifiConfiguration localWifiConfiguration;
        do {
            if(!localIterator.hasNext()) return null;
            localWifiConfiguration = (WifiConfiguration) localIterator.next();
        }while(!localWifiConfiguration.SSID.equals("\"" + str + "\""));
        return localWifiConfiguration;
    }
                                                                                                                                                           
    /**鎖定WifiLock,當下載大文件時需要鎖定 **/
    public void AcquireWifiLock() {
        this.mWifilock.acquire();
    }
    /**創建一個WifiLock**/
    public void CreateWifiLock() {
        this.mWifilock = this.mWifiManager.createWifiLock("Test");
    }
    /**解鎖WifiLock**/
    public void ReleaseWifilock() {
        if(mWifilock.isHeld()) { //判斷時候鎖定
            mWifilock.acquire();
        }
    }
                                                                                                                                                           
                                                                                                                                                           
    /**打開Wifi**/
    public void OpenWifi() {
        if(!this.mWifiManager.isWifiEnabled()){ //當前wifi不可用
            this.mWifiManager.setWifiEnabled(true);
        }
    }
    /**關閉Wifi**/
    public void closeWifi() {
        if(mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }
    }
    /**端口指定id的wifi**/
    public void disconnectWifi(int paramInt) {
        this.mWifiManager.disableNetwork(paramInt);
    }
                                                                                                                                                           
    /**添加指定網絡**/
    public void addNetwork(WifiConfiguration paramWifiConfiguration) {
        int i = mWifiManager.addNetwork(paramWifiConfiguration);
        mWifiManager.enableNetwork(i, true);
    }
                                                                                                                                                           
    /**
     * 連接指定配置好的網絡
     * @param index 配置好網絡的ID
     */
    public void connectConfiguration(int index) { 
        // 索引大於配置好的網絡索引返回  
        if (index > mWifiConfiguration.size()) { 
            return; 
        } 
        //連接配置好的指定ID的網絡  
        mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, true); 
    }
                                                                                                                                                           
    /**
     * 根據wifi信息創建或關閉一個熱點
     * @param paramWifiConfiguration
     * @param paramBoolean 關閉標志
     */
    public void createWifiAP(WifiConfiguration paramWifiConfiguration,boolean paramBoolean) {
        try {
            Class localClass = this.mWifiManager.getClass();
            Class[] arrayOfClass = new Class[2];
            arrayOfClass[0] = WifiConfiguration.class;
            arrayOfClass[1] = Boolean.TYPE;
            Method localMethod = localClass.getMethod("setWifiApEnabled",arrayOfClass);
            WifiManager localWifiManager = this.mWifiManager;
            Object[] arrayOfObject = new Object[2];
            arrayOfObject[0] = paramWifiConfiguration;
            arrayOfObject[1] = Boolean.valueOf(paramBoolean);
            localMethod.invoke(localWifiManager, arrayOfObject);
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 創建一個wifi信息
     * @param ssid 名稱
     * @param passawrd 密碼
     * @param paramInt 有3個參數,1是無密碼,2是簡單密碼,3是wap加密
     * @param type 是"ap"還是"wifi"
     * @return
     */
    public WifiConfiguration createWifiInfo(String ssid, String passawrd,int paramInt, String type) {
        //配置網絡信息類
        WifiConfiguration localWifiConfiguration1 = new WifiConfiguration();
        //設置配置網絡屬性
        localWifiConfiguration1.allowedAuthAlgorithms.clear();
        localWifiConfiguration1.allowedGroupCiphers.clear();
        localWifiConfiguration1.allowedKeyManagement.clear();
        localWifiConfiguration1.allowedPairwiseCiphers.clear();
        localWifiConfiguration1.allowedProtocols.clear();
                                                                                                                                                               
        if(type.equals("wt")) { //wifi連接
            localWifiConfiguration1.SSID = ("\"" + ssid + "\"");
            WifiConfiguration localWifiConfiguration2 = isExsits(ssid);
            if(localWifiConfiguration2 != null) {
                mWifiManager.removeNetwork(localWifiConfiguration2.networkId); //從列表中刪除指定的網絡配置網絡
            }
            if(paramInt == 1) { //沒有密碼
                localWifiConfiguration1.wepKeys[0] = "";
                localWifiConfiguration1.allowedKeyManagement.set(0);
                localWifiConfiguration1.wepTxKeyIndex = 0;
            } else if(paramInt == 2) { //簡單密碼
                localWifiConfiguration1.hiddenSSID = true;
                localWifiConfiguration1.wepKeys[0] = ("\"" + passawrd + "\"");
            } else { //wap加密
                localWifiConfiguration1.preSharedKey = ("\"" + passawrd + "\"");
                localWifiConfiguration1.hiddenSSID = true;
                localWifiConfiguration1.allowedAuthAlgorithms.set(0);
                localWifiConfiguration1.allowedGroupCiphers.set(2);
                localWifiConfiguration1.allowedKeyManagement.set(1);
                localWifiConfiguration1.allowedPairwiseCiphers.set(1);
                localWifiConfiguration1.allowedGroupCiphers.set(3);
                localWifiConfiguration1.allowedPairwiseCiphers.set(2);
            }
        }else {//"ap" wifi熱點
            localWifiConfiguration1.SSID = ssid;
            localWifiConfiguration1.allowedAuthAlgorithms.set(1);
            localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            localWifiConfiguration1.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            localWifiConfiguration1.allowedKeyManagement.set(0);
            localWifiConfiguration1.wepTxKeyIndex = 0;
            if (paramInt == 1) {  //沒有密碼
                localWifiConfiguration1.wepKeys[0] = "";
                localWifiConfiguration1.allowedKeyManagement.set(0);
                localWifiConfiguration1.wepTxKeyIndex = 0;
            } else if (paramInt == 2) { //簡單密碼
                localWifiConfiguration1.hiddenSSID = true;//網絡上不廣播ssid
                localWifiConfiguration1.wepKeys[0] = passawrd;
            } else if (paramInt == 3) {//wap加密
                localWifiConfiguration1.preSharedKey = passawrd;
                localWifiConfiguration1.allowedAuthAlgorithms.set(0);
                localWifiConfiguration1.allowedProtocols.set(1);
                localWifiConfiguration1.allowedProtocols.set(0);
                localWifiConfiguration1.allowedKeyManagement.set(1);
                localWifiConfiguration1.allowedPairwiseCiphers.set(2);
                localWifiConfiguration1.allowedPairwiseCiphers.set(1);
            }
        }
        return localWifiConfiguration1;
    }
                                                                                                                                                           
    /**獲取熱點名**/
    public String getApSSID() {
        try {
            Method localMethod = this.mWifiManager.getClass().getDeclaredMethod("getWifiApConfiguration", new Class[0]);
            if (localMethod == null) return null;
            Object localObject1 = localMethod.invoke(this.mWifiManager,new Object[0]);
            if (localObject1 == null) return null;
            WifiConfiguration localWifiConfiguration = (WifiConfiguration) localObject1;
            if (localWifiConfiguration.SSID != null) return localWifiConfiguration.SSID;
            Field localField1 = WifiConfiguration.class .getDeclaredField("mWifiApProfile");
            if (localField1 == null) return null;
            localField1.setAccessible(true);
            Object localObject2 = localField1.get(localWifiConfiguration);
            localField1.setAccessible(false);
            if (localObject2 == null)  return null;
            Field localField2 = localObject2.getClass().getDeclaredField("SSID");
            localField2.setAccessible(true);
            Object localObject3 = localField2.get(localObject2);
            if (localObject3 == null) return null;
            localField2.setAccessible(false);
            String str = (String) localObject3;
            return str;
        } catch (Exception localException) {
        }
        return null;
    }
                                                                                                                                                           
    /**獲取wifi名**/
    public String getBSSID() {
        if (this.mWifiInfo == null)
            return "NULL";
        return this.mWifiInfo.getBSSID();
    }
                                                                                                                                                         
   /**得到配置好的網絡 **/
    public List<WifiConfiguration> getConfiguration() {
        return this.mWifiConfiguration;
    }
                                                                                                                                                           
    /**獲取ip地址**/
    public int getIPAddress() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
    }
    /**獲取物理地址(Mac)**/
    public String getMacAddress() {
         return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
    }   
                                                                                                                                                             
    /**獲取網絡id**/
    public int getNetworkId() {
         return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
    }
    /**獲取熱點創建狀態**/
    public int getWifiApState() {
        try {
            int i = ((Integer) this.mWifiManager.getClass()
                    .getMethod("getWifiApState", new Class[0])
                    .invoke(this.mWifiManager, new Object[0])).intValue();
            return i;
        } catch (Exception localException) {
        }
        return 4;   //未知wifi網卡狀態
    }
    /**獲取wifi連接信息**/
    public WifiInfo getWifiInfo() {
        return this.mWifiManager.getConnectionInfo();
    }
    /** 得到網絡列表**/
    public List<ScanResult> getWifiList() {
        return this.mWifiList;
    }
                                                                                                                                                         
    /**查看掃描結果**/
    public StringBuilder lookUpScan() {
        StringBuilder localStringBuilder = new StringBuilder();
        for (int i = 0; i < mWifiList.size(); i++)
        {
            localStringBuilder.append("Index_"+new Integer(i + 1).toString() + ":");
            //將ScanResult信息轉換成一個字符串包
            //其中把包括:BSSID、SSID、capabilities、frequency、level
            localStringBuilder.append((mWifiList.get(i)).toString());
            localStringBuilder.append("\n");
        }
        return localStringBuilder;
    }
                                                                                                                                                             
    /** 設置wifi搜索結果 **/
    public void setWifiList() {
        this.mWifiList = this.mWifiManager.getScanResults();
    }
    /**開始搜索wifi**/
    public void startScan() {
        this.mWifiManager.startScan();
    }
    /**得到接入點的BSSID**/
    public String GetBSSID() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
    }
}

 

最後,成功連接到wifi後,通過本機IP地址便可以進行相關網絡開發,在下一篇中我會講解一個WIFI熱點搜索、創建、連接的Demo(https://smallwoniu.blog.51cto.com/3911954/1338618),希望能幫助到大傢!

You May Also Like