溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

【移動(dòng)開發(fā)】Android中WIFI開發(fā)總結(jié)(一)

發(fā)布時(shí)間:2020-07-05 05:18:42 來(lái)源:網(wǎng)絡(luò) 閱讀:45528 作者:zhf651555765 欄目:開發(fā)技術(shù)

       WIFI就是一種無(wú)線聯(lián)網(wǎng)技術(shù),常見的是使用無(wú)線路由器。那么在這個(gè)無(wú)線路由器的信號(hào)覆蓋的范圍內(nèi)都可以采用WIFI連接的方式進(jìn)行聯(lián)網(wǎng)。如果無(wú)線路由器連接了一個(gè)ADSL線路或其他的聯(lián)網(wǎng)線路,則又被稱為“熱點(diǎn)”。


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


1.ScanResult

   主要用來(lái)描述已經(jīng)檢測(cè)出的接入點(diǎn),包括接入點(diǎn)的地址,接入點(diǎn)的名稱,身份認(rèn)證,頻率,信號(hào)強(qiáng)度等信息。其實(shí)就是通過(guò)wifi 硬件的掃描來(lái)獲取一些周邊的wifi 熱點(diǎn)的信息。


2.WifiConfiguration

Wifi網(wǎng)絡(luò)的配置,包括安全設(shè)置等,在我們連通一個(gè)wifi 接入點(diǎn)的時(shí)候,需要獲取到的一些信息。主要包含四個(gè)屬性:

BSSID:

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

networkid:網(wǎng)絡(luò)ID。

PreSharedKey:無(wú)線網(wǎng)絡(luò)的安全認(rèn)證模式。

SSID:SSID(Service Set Identif)用于標(biāo)識(shí)無(wú)線局域網(wǎng),SSID不同的無(wú)線網(wǎng)絡(luò)是無(wú)法進(jìn)行互訪的。


3.WifiInfo

   wifi無(wú)線連接的描述,包括(接入點(diǎn),網(wǎng)絡(luò)連接狀態(tài),隱藏的接入點(diǎn),IP地址,連接速度,MAC地址,網(wǎng)絡(luò)ID,信號(hào)強(qiáng)度等信息)。這里簡(jiǎn)單介紹一下WifiManager中常用的方法:

getSSID() 獲得SSID(熱點(diǎn)名稱)

getBSSID()

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


4.WifiManager

     wifi連接統(tǒng)一管理類,獲取WIFI網(wǎng)卡的狀態(tài)(WIFI網(wǎng)卡的狀態(tài)是由一系列的×××常量來(lái)表示的)

WIFI_STATE_DISABLING = 0WIFI網(wǎng)卡正在關(guān)閉
WIFI_STATE_DISABLED = 1WIFI網(wǎng)卡不可用
WIFI_STATE_ENABLING = 2WIFI網(wǎng)正在打開 (WIFI啟動(dòng)需要一段時(shí)間)
WIFI_STATE_ENABLED = 3WIFI網(wǎng)卡可用
WIFI_STATE_UNKNOWN = 4未知網(wǎng)卡狀態(tài)
WIFI_AP_STATE_DISABLING = 10WIFI熱點(diǎn)正在關(guān)閉
WIFI_AP_STATE_DISABLED = 11WIFI熱點(diǎn)不可用
WIFI_AP_STATE_ENABLING = 12WIFI熱點(diǎn)正在打開
WIFI_AP_STATE_ENABLED = 13WIFI熱點(diǎn)可用


5. 在AndroidManifest.xml進(jìn)行對(duì)WIFI操作的權(quán)限設(shè)置

<!-- 以下是使用wifi訪問網(wǎng)絡(luò)所需的權(quán)限 -->
    <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>


 下面是匯總的一個(gè)wifi管理工具類,我完善了一下,并加上了詳細(xì)的注解,很實(shí)用的!

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; //無(wú)線網(wǎng)絡(luò)配置信息類集合(網(wǎng)絡(luò)連接列表)
    private List<ScanResult> mWifiList; //檢測(cè)到接入點(diǎn)信息類 集合
                                                                                                                                                          
    //描述任何Wifi連接狀態(tài)
    private WifiInfo mWifiInfo;
                                                                                                                                                          
    WifiManager.WifiLock mWifilock; //能夠阻止wifi進(jìn)入睡眠狀態(tài),使wifi一直處于活躍狀態(tài)
    public WifiManager mWifiManager;
                                                                                                                                                          
    /**
     * 獲取該類的實(shí)例(懶漢)
     * @param context
     * @return
     */
    public static WifiAdmin getInstance(Context context) {
        if(wifiAdmin == null) {
            wifiAdmin = new WifiAdmin(context);
        }
        return wifiAdmin;
    }
    private WifiAdmin(Context context) {
        //獲取系統(tǒng)Wifi服務(wù)   WIFI_SERVICE
        this.mWifiManager = (WifiManager) context.getSystemService("wifi");
        //獲取連接信息
        this.mWifiInfo = this.mWifiManager.getConnectionInfo();
    }
                                                                                                                                                          
    /**
     * 是否存在網(wǎng)絡(luò)信息
     * @param str  熱點(diǎn)名稱
     * @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,當(dāng)下載大文件時(shí)需要鎖定 **/
    public void AcquireWifiLock() {
        this.mWifilock.acquire();
    }
    /**創(chuàng)建一個(gè)WifiLock**/
    public void CreateWifiLock() {
        this.mWifilock = this.mWifiManager.createWifiLock("Test");
    }
    /**解鎖WifiLock**/
    public void ReleaseWifilock() {
        if(mWifilock.isHeld()) { //判斷時(shí)候鎖定
            mWifilock.acquire();
        }
    }
                                                                                                                                                          
                                                                                                                                                          
    /**打開Wifi**/
    public void OpenWifi() {
        if(!this.mWifiManager.isWifiEnabled()){ //當(dāng)前wifi不可用
            this.mWifiManager.setWifiEnabled(true);
        }
    }
    /**關(guān)閉Wifi**/
    public void closeWifi() {
        if(mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }
    }
    /**端口指定id的wifi**/
    public void disconnectWifi(int paramInt) {
        this.mWifiManager.disableNetwork(paramInt);
    }
                                                                                                                                                          
    /**添加指定網(wǎng)絡(luò)**/
    public void addNetwork(WifiConfiguration paramWifiConfiguration) {
        int i = mWifiManager.addNetwork(paramWifiConfiguration);
        mWifiManager.enableNetwork(i, true);
    }
                                                                                                                                                          
    /**
     * 連接指定配置好的網(wǎng)絡(luò)
     * @param index 配置好網(wǎng)絡(luò)的ID
     */
    public void connectConfiguration(int index) { 
        // 索引大于配置好的網(wǎng)絡(luò)索引返回  
        if (index > mWifiConfiguration.size()) { 
            return; 
        } 
        //連接配置好的指定ID的網(wǎng)絡(luò)  
        mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, true); 
    }
                                                                                                                                                          
    /**
     * 根據(jù)wifi信息創(chuàng)建或關(guān)閉一個(gè)熱點(diǎn)
     * @param paramWifiConfiguration
     * @param paramBoolean 關(guān)閉標(biāo)志
     */
    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();
        }
    }
    /**
     * 創(chuàng)建一個(gè)wifi信息
     * @param ssid 名稱
     * @param passawrd 密碼
     * @param paramInt 有3個(gè)參數(shù),1是無(wú)密碼,2是簡(jiǎn)單密碼,3是wap加密
     * @param type 是"ap"還是"wifi"
     * @return
     */
    public WifiConfiguration createWifiInfo(String ssid, String passawrd,int paramInt, String type) {
        //配置網(wǎng)絡(luò)信息類
        WifiConfiguration localWifiConfiguration1 = new WifiConfiguration();
        //設(shè)置配置網(wǎng)絡(luò)屬性
        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); //從列表中刪除指定的網(wǎng)絡(luò)配置網(wǎng)絡(luò)
            }
            if(paramInt == 1) { //沒有密碼
                localWifiConfiguration1.wepKeys[0] = "";
                localWifiConfiguration1.allowedKeyManagement.set(0);
                localWifiConfiguration1.wepTxKeyIndex = 0;
            } else if(paramInt == 2) { //簡(jiǎn)單密碼
                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熱點(diǎn)
            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) { //簡(jiǎn)單密碼
                localWifiConfiguration1.hiddenSSID = true;//網(wǎng)絡(luò)上不廣播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;
    }
                                                                                                                                                          
    /**獲取熱點(diǎn)名**/
    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();
    }
                                                                                                                                                        
   /**得到配置好的網(wǎng)絡(luò) **/
    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();
    }   
                                                                                                                                                            
    /**獲取網(wǎng)絡(luò)id**/
    public int getNetworkId() {
         return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
    }
    /**獲取熱點(diǎn)創(chuàng)建狀態(tài)**/
    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網(wǎng)卡狀態(tài)
    }
    /**獲取wifi連接信息**/
    public WifiInfo getWifiInfo() {
        return this.mWifiManager.getConnectionInfo();
    }
    /** 得到網(wǎng)絡(luò)列表**/
    public List<ScanResult> getWifiList() {
        return this.mWifiList;
    }
                                                                                                                                                        
    /**查看掃描結(jié)果**/
    public StringBuilder lookUpScan() {
        StringBuilder localStringBuilder = new StringBuilder();
        for (int i = 0; i < mWifiList.size(); i++)
        {
            localStringBuilder.append("Index_"+new Integer(i + 1).toString() + ":");
            //將ScanResult信息轉(zhuǎn)換成一個(gè)字符串包
            //其中把包括:BSSID、SSID、capabilities、frequency、level
            localStringBuilder.append((mWifiList.get(i)).toString());
            localStringBuilder.append("\n");
        }
        return localStringBuilder;
    }
                                                                                                                                                            
    /** 設(shè)置wifi搜索結(jié)果 **/
    public void setWifiList() {
        this.mWifiList = this.mWifiManager.getScanResults();
    }
    /**開始搜索wifi**/
    public void startScan() {
        this.mWifiManager.startScan();
    }
    /**得到接入點(diǎn)的BSSID**/
    public String GetBSSID() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
    }
}

更多相關(guān)知識(shí)點(diǎn)文章:

android開發(fā)教程之如何實(shí)現(xiàn)wifi開發(fā)示例

android開發(fā)如何實(shí)現(xiàn)在Wifi下獲取本地IP地址

最后,成功連接到wifi后,通過(guò)本機(jī)IP地址便可以進(jìn)行相關(guān)網(wǎng)絡(luò)開發(fā),在下一篇中我會(huì)講解一個(gè)WIFI熱點(diǎn)搜索、創(chuàng)建、連接的Demo(http://smallwoniu.blog.51cto.com/3911954/1338618),希望能幫助到大家!



向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI