Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android WiFi/WiFi熱點開發總結

Android WiFi/WiFi熱點開發總結

編輯:關於Android編程

首先看一下WiFi的自我介紹:

Wi-Fi是一種允許電子設備連接到一個無線局域網(WLAN)的技術,通常使用2.4G UHF或5G SHF ISM 射頻頻段。連接到無線局域網通常是有密碼保護的;但也可是開放的,這樣就允許任何在WLAN范圍內的設備可以連接上。

wifi可以說是Android開發中非常重要的一部分了,這裡用到了一個WifiAdmin工具類。

package com.qdzn.home.wifi;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;

import java.lang.reflect.Method;
import java.util.List;

/**
 * wifi工具類
 */
public class WifiAdmin {

    public static final String SSID = "nexus";
    public static final String PassWord = "12345678";
    private WifiManager mWifiManager;
    // 定義WifiInfo對象
    private WifiInfo mWifiInfo;
    // 掃描出的網絡連接列表
    private List mWifiList;
    // 網絡連接列表
    private List mWifiConfiguration;
    // 定義一個WifiLock
    WifiLock mWifiLock;

    // 構造器
    public WifiAdmin(Context context) {
        // 取得WifiManager對象
        mWifiManager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        // 取得WifiInfo對象
        mWifiInfo = mWifiManager.getConnectionInfo();
    }

    // 打開WIFI
    public void openWifi() {
        if (!mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(true);
            //開始掃描WIFI
            startScan();
        }
    }

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

    //創建熱點
    public void createAp() {
        if (mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }
        try {
            WifiConfiguration apConfiguration = new WifiConfiguration();
            apConfiguration.SSID = WifiAdmin.SSID;
            apConfiguration.preSharedKey = WifiAdmin.PassWord;
            apConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            Method method = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
            method.invoke(mWifiManager, apConfiguration, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 關閉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 (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 判斷熱點是否打開
     *
     * @return
     */
    public boolean isWifiApEnabled() {
        try {
            Method method = mWifiManager.getClass().getMethod("isWifiApEnabled");
            method.setAccessible(true);
            return (Boolean) method.invoke(mWifiManager);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    // 檢查當前WIFI狀態
    public int checkState() {
        return mWifiManager.getWifiState();
    }

    // 鎖定WifiLock
    public void acquireWifiLock() {
        mWifiLock.acquire();
    }

    // 解鎖WifiLock
    public void releaseWifiLock() {
        // 判斷時候鎖定
        if (mWifiLock.isHeld()) {
            mWifiLock.acquire();
        }
    }

    // 創建一個WifiLock
    public void creatWifiLock() {
        mWifiLock = mWifiManager.createWifiLock("Test");
    }

    // 得到配置好的網絡
    public List getConfiguration() {
        return mWifiConfiguration;
    }

    // 指定配置好的網絡進行連接
    public void connectConfiguration(int index) {
        // 索引大於配置好的網絡索引返回
        if (index > mWifiConfiguration.size()) {
            return;
        }
        // 連接配置好的指定ID的網絡
        mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, true);
    }

    /**
     * 掃描WIFI
     */
    public void startScan() {
        mWifiManager.startScan();
        // 得到掃描結果
        mWifiList = mWifiManager.getScanResults();
        // 得到配置好的網絡連接
        mWifiConfiguration = mWifiManager.getConfiguredNetworks();
    }

    // 得到網絡列表
    public List getWifiList() {
        return mWifiList;
    }

    // 查看掃描結果
    public StringBuilder lookUpScan() {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < mWifiList.size(); i++) {
            stringBuilder
                    .append("Index_" + new Integer(i + 1).toString() + ":");
            // 將ScanResult信息轉換成一個字符串包
            // 其中把包括:BSSID、SSID、capabilities、frequency、level
            stringBuilder.append((mWifiList.get(i)).toString());
            stringBuilder.append("/n");
        }
        return stringBuilder;
    }

    // 得到MAC地址
    public String getMacAddress() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
    }

    // 得到接入點的BSSID
    public String getBSSID() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
    }

    // 得到IP地址
    public int getIPAddress() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
    }

    // 得到連接的ID
    public int getNetworkId() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
    }

    // 得到WifiInfo的所有信息包
    public String getWifiInfo() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
    }

    // 添加一個網絡並連接
    public void addNetwork(WifiConfiguration wcg) {
        System.out.println("進行添加網絡:");
        int wcgID = mWifiManager.addNetwork(wcg);
        boolean b = mWifiManager.enableNetwork(wcgID, true);
        System.out.println("b--" + b);
    }

    // 斷開指定ID的網絡
    public void disconnectWifi(int netId) {
        mWifiManager.disableNetwork(netId);
        mWifiManager.disconnect();
    }

    // 然後是一個實際應用方法
    public WifiConfiguration CreateWifiInfo(String SSID, String Password, int Type) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";
        WifiConfiguration tempConfig = this.IsExsits(SSID);
        if (tempConfig != null) {
            mWifiManager.removeNetwork(tempConfig.networkId);
        }

        if (Type == 1) // WIFICIPHER_NOPASS
        {
            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == 2) // 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;
        }
        if (Type == 3) // WIFICIPHER_WPA
        {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.OPEN);
            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.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }

        return config;
    }

    private WifiConfiguration IsExsits(String SSID) {
        List existingConfigs = mWifiManager
                .getConfiguredNetworks();
        for (WifiConfiguration existingConfig : existingConfigs) {
            System.out.println(existingConfig.SSID);
            if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
                System.out.println("拿到了相同配置對象:" + existingConfig.SSID);
                return existingConfig;
            }
        }
        return null;
    }

    /**
     * ip地址轉換
     * @param i
     * @return
     */
    public static String intToIp(int i) {
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 24) & 0xFF);
    }
}

使用方法

1.初始化工具類

//首先需要獲取到wifi管理者,初始化工具類
 WifiAdmin wifiAdmin = new WifiAdmin(this);

  // 工具類初始化
    public WifiAdmin(Context context) {
        // 取得WifiManager對象
        mWifiManager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        // 取得WifiInfo對象
        mWifiInfo = mWifiManager.getConnectionInfo();
    }

2.開啟wifi

 //打開wifi
 wifiAdmin.openWifi();

3.連接熱點

 //連接熱點之前我們需要先掃描周圍熱點
    public void connect() {
    wifiAdmin.startScan();
        new Thread(new Runnable() {
            @Override
            public void run() {
                           wifiAdmin.addNetwork(wifiAdmin.CreateWifiInfo(WifiAdmin.SSID, WifiAdmin.PassWord, 3));
            }
        }).start();

    }

4.關閉Wifi

wifiAdmin.closeWifi();

5.創建熱點

wifiAdmin.createAp();

6.關閉熱點

wifiAdmin.closeWifiAp();

對於Wifi和Wifi熱點的基本使用就這些,重點都在WifiAdmin工具類中,下面在來說說如何使用廣播來監聽他們的狀態改變。

注冊廣播監聽WIFI連接狀態改變

1 . 需要的權限


2 . 注冊廣播


     
         
         
         
     

3 . 廣播接收者

public class WifiReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
            NetworkInfo info =intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
                /**
                 * wifi斷開連接
                 */
            } else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
                WifiManager wifiManager=(WifiManager)context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                /**
                 * wifi以連接wifiInfo.getSSID();獲取連接的wifi名稱
                 */
                     Log.d("TAG",wifiInfo.getSSID());
                }
            }else if(intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {//wifi打開與否
            int wifistate = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED);
            if (wifistate == WifiManager.WIFI_STATE_DISABLED) {
                /**
                 * 系統關閉wifi
                 */
            } else if (wifistate == WifiManager.WIFI_STATE_ENABLED) {
                /**
                 * 系統開啟wifi
                 */
            }
        }
    }
}

以上就是根據廣播接受者來獲取WIFI的狀態,下面在來說說監聽WIFI熱點的狀態

1.廣播注冊(需要注意的是這個Action自動提示裡根本就找不到,貌似是被隱藏了起來)


    
        
    

2 . 廣播接收者

public class WifiApReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if ("android.net.wifi.WIFI_AP_STATE_CHANGED".equals(action)) {
            //便攜式熱點的狀態為:10---正在關閉;11---已關閉;12---正在開啟;13---已開啟
            int state = intent.getIntExtra("wifi_state", 0);
            Log.d("TAG", state + "---");
        }
    }
}

以上就是使用廣播接收者來獲取WIFI和WIFI熱點的狀態……

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved