`
forhope
  • 浏览: 367053 次
  • 性别: Icon_minigender_1
  • 来自: 帝都
社区版块
存档分类
最新评论

Android WIFI模块解析

 
阅读更多
Android中的AP扫描结果,通过WifiNative的JNI调用,实际调用wpa_supplicant的相应命令,并返回字符串给JNI方法,下面是对该字符串的解析函数:

private static final Pattern scanResultPattern = Pattern.compile("\t+");
/**
     * Parse the scan result line passed to us by wpa_supplicant (helper).
     * @param line the line to parse
     * @return the {@link ScanResult} object
     */
    private ScanResult parseScanResult(String line) {
        ScanResult scanResult = null;
        if (line != null) {
            /*
             * Cache implementation (LinkedHashMap) is not synchronized, thus,
             * must synchronized here!
             */
            synchronized (mScanResultCache) {
                String[] result = scanResultPattern.split(line);
                if (3 <= result.length && result.length <= 5) {
                    String bssid = result[0];
                    // bssid | frequency | level | flags | ssid
                    int frequency;
                    int level;
                    try {
                        frequency = Integer.parseInt(result[1]);
                        level = Integer.parseInt(result[2]);
                        /* some implementations avoid negative values by adding 256
                         * so we need to adjust for that here.
                         */
                        if (level > 0) level -= 256;
                    } catch (NumberFormatException e) {
                        frequency = 0;
                        level = 0;
                    }

                    /*
                     * The formatting of the results returned by
                     * wpa_supplicant is intended to make the fields
                     * line up nicely when printed,
                     * not to make them easy to parse. So we have to
                     * apply some heuristics to figure out which field
                     * is the SSID and which field is the flags.
                     */
                    String ssid;
                    String flags;
                    if (result.length == 4) {
                        if (result[3].charAt(0) == '[') {
                            flags = result[3];
                            ssid = "";
                        } else {
                            flags = "";
                            ssid = result[3];
                        }
                    } else if (result.length == 5) {
                        flags = result[3];
                        ssid = result[4];
                    } else {
                        // Here, we must have 3 fields: no flags and ssid
                        // set
                        flags = "";
                        ssid = "";
                    }

                    // bssid + ssid is the hash key
                    String key = bssid + ssid;
                    scanResult = mScanResultCache.get(key);
                    if (scanResult != null) {
                        scanResult.level = level;
                        scanResult.SSID = ssid;
                        scanResult.capabilities = flags;
                        scanResult.frequency = frequency;
                    } else {
                        // Do not add scan results that have no SSID set
                        if (0 < ssid.trim().length()) {
                            scanResult =
                                new ScanResult(
                                    ssid, bssid, flags, level, frequency);
                            mScanResultCache.put(key, scanResult);
                        }
                    }
                } else {
                    Slog.w(TAG, "Misformatted scan result text with " +
                          result.length + " fields: " + line);
                }
            }
        }

        return scanResult;
    }


WIFI添加一个网络配置,返回生成的网络ID
/**
     * see {@link android.net.wifi.WifiManager#addOrUpdateNetwork(WifiConfiguration)}
     * @return the supplicant-assigned identifier for the new or updated
     * network if the operation succeeds, or {@code -1} if it fails
     */
    public int addOrUpdateNetwork(WifiConfiguration config) {
        enforceChangePermission();

        /*
         * If the supplied networkId is -1, we create a new empty
         * network configuration. Otherwise, the networkId should
         * refer to an existing configuration.
         */
        int netId = config.networkId;
        boolean newNetwork = netId == -1;
        boolean doReconfig = false;
        // networkId of -1 means we want to create a new network
        synchronized (mWifiStateTracker) {
            if (newNetwork) {
                netId = mWifiStateTracker.addNetwork();
                if (netId < 0) {
                    if (DBG) {
                        Slog.d(TAG, "Failed to add a network!");
                    }
                    return -1;
                }
                doReconfig = true;
            }
            mNeedReconfig = mNeedReconfig || doReconfig;
        }

        setVariables: {
            /*
             * Note that if a networkId for a non-existent network
             * was supplied, then the first setNetworkVariable()
             * will fail, so we don't bother to make a separate check
             * for the validity of the ID up front.
             */
            if (config.SSID != null &&
                    !mWifiStateTracker.setNetworkVariable(
                        netId,
                        WifiConfiguration.ssidVarName,
                        config.SSID)) {
                if (DBG) {
                    Slog.d(TAG, "failed to set SSID: "+config.SSID);
                }
                break setVariables;
            }

            if (config.BSSID != null &&
                    !mWifiStateTracker.setNetworkVariable(
                        netId,
                        WifiConfiguration.bssidVarName,
                        config.BSSID)) {
                if (DBG) {
                    Slog.d(TAG, "failed to set BSSID: "+config.BSSID);
                }
                break setVariables;
            }

            String allowedKeyManagementString =
                makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
            if (config.allowedKeyManagement.cardinality() != 0 &&
                    !mWifiStateTracker.setNetworkVariable(
                        netId,
                        WifiConfiguration.KeyMgmt.varName,
                        allowedKeyManagementString)) {
                if (DBG) {
                    Slog.d(TAG, "failed to set key_mgmt: "+
                            allowedKeyManagementString);
                }
                break setVariables;
            }

            String allowedProtocolsString =
                makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
            if (config.allowedProtocols.cardinality() != 0 &&
                    !mWifiStateTracker.setNetworkVariable(
                        netId,
                        WifiConfiguration.Protocol.varName,
                        allowedProtocolsString)) {
                if (DBG) {
                    Slog.d(TAG, "failed to set proto: "+
                            allowedProtocolsString);
                }
                break setVariables;
            }

            String allowedAuthAlgorithmsString =
                makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
            if (config.allowedAuthAlgorithms.cardinality() != 0 &&
                    !mWifiStateTracker.setNetworkVariable(
                        netId,
                        WifiConfiguration.AuthAlgorithm.varName,
                        allowedAuthAlgorithmsString)) {
                if (DBG) {
                    Slog.d(TAG, "failed to set auth_alg: "+
                            allowedAuthAlgorithmsString);
                }
                break setVariables;
            }

            String allowedPairwiseCiphersString =
                makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
            if (config.allowedPairwiseCiphers.cardinality() != 0 &&
                    !mWifiStateTracker.setNetworkVariable(
                        netId,
                        WifiConfiguration.PairwiseCipher.varName,
                        allowedPairwiseCiphersString)) {
                if (DBG) {
                    Slog.d(TAG, "failed to set pairwise: "+
                            allowedPairwiseCiphersString);
                }
                break setVariables;
            }

            String allowedGroupCiphersString =
                makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
            if (config.allowedGroupCiphers.cardinality() != 0 &&
                    !mWifiStateTracker.setNetworkVariable(
                        netId,
                        WifiConfiguration.GroupCipher.varName,
                        allowedGroupCiphersString)) {
                if (DBG) {
                    Slog.d(TAG, "failed to set group: "+
                            allowedGroupCiphersString);
                }
                break setVariables;
            }

            // Prevent client screw-up by passing in a WifiConfiguration we gave it
            // by preventing "*" as a key.
            if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
                    !mWifiStateTracker.setNetworkVariable(
                        netId,
                        WifiConfiguration.pskVarName,
                        config.preSharedKey)) {
                if (DBG) {
                    Slog.d(TAG, "failed to set psk: "+config.preSharedKey);
                }
                break setVariables;
            }

            boolean hasSetKey = false;
            if (config.wepKeys != null) {
                for (int i = 0; i < config.wepKeys.length; i++) {
                    // Prevent client screw-up by passing in a WifiConfiguration we gave it
                    // by preventing "*" as a key.
                    if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
                        if (!mWifiStateTracker.setNetworkVariable(
                                    netId,
                                    WifiConfiguration.wepKeyVarNames[i],
                                    config.wepKeys[i])) {
                            if (DBG) {
                                Slog.d(TAG,
                                        "failed to set wep_key"+i+": " +
                                        config.wepKeys[i]);
                            }
                            break setVariables;
                        }
                        hasSetKey = true;
                    }
                }
            }

            if (hasSetKey) {
                if (!mWifiStateTracker.setNetworkVariable(
                            netId,
                            WifiConfiguration.wepTxKeyIdxVarName,
                            Integer.toString(config.wepTxKeyIndex))) {
                    if (DBG) {
                        Slog.d(TAG,
                                "failed to set wep_tx_keyidx: "+
                                config.wepTxKeyIndex);
                    }
                    break setVariables;
                }
            }

            if (!mWifiStateTracker.setNetworkVariable(
                        netId,
                        WifiConfiguration.priorityVarName,
                        Integer.toString(config.priority))) {
                if (DBG) {
                    Slog.d(TAG, config.SSID + ": failed to set priority: "
                            +config.priority);
                }
                break setVariables;
            }

            if (config.hiddenSSID && !mWifiStateTracker.setNetworkVariable(
                        netId,
                        WifiConfiguration.hiddenSSIDVarName,
                        Integer.toString(config.hiddenSSID ? 1 : 0))) {
                if (DBG) {
                    Slog.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
                            config.hiddenSSID);
                }
                break setVariables;
            }

            for (WifiConfiguration.EnterpriseField field
                    : config.enterpriseFields) {
                String varName = field.varName();
                String value = field.value();
                if (value != null) {
                    if (field != config.eap) {
                        value = (value.length() == 0) ? "NULL" : convertToQuotedString(value);
                    }
                    if (!mWifiStateTracker.setNetworkVariable(
                                netId,
                                varName,
                                value)) {
                        if (DBG) {
                            Slog.d(TAG, config.SSID + ": failed to set " + varName +
                                    ": " + value);
                        }
                        break setVariables;
                    }
                }
            }
            return netId;
        }


认证类型管理类:

/**
     * Recognized key management schemes.
     */
    public static class KeyMgmt {
        private KeyMgmt() { }

        /** WPA is not used; plaintext or static WEP could be used. */
        public static final int NONE = 0;
        /** WPA pre-shared key (requires {@code preSharedKey} to be specified). */
        public static final int WPA_PSK = 1;
        /** WPA using EAP authentication. Generally used with an external authentication server. */
        public static final int WPA_EAP = 2;
        /** IEEE 802.1X using EAP authentication and (optionally) dynamically
         * generated WEP keys. */
        public static final int IEEE8021X = 3;

        public static final String varName = "key_mgmt";

        public static final String[] strings = { "NONE", "WPA_PSK", "WPA_EAP", "IEEE8021X" };
    }
分享到:
评论

相关推荐

    深入理解Android:WiFi模块 NFC和GPS卷.邓凡平(文字版).pdf

    《深入理解Android:WiFi模块 NFC和GPS卷》是由邓凡平编著的一本技术书籍,主要探讨了Android系统中三个重要的无线通信技术:WiFi、NFC(近场通信)和GPS(全球定位系统)。这本书以文字版的形式,深入浅出地讲解了...

    Android-WIFI.rar_WiFi模块程序_android wifi_android wifi slam_android

    在Android系统中,WiFi模块是实现无线网络连接的关键部分,对于开发者来说,理解和掌握如何进行Android WiFi开发至关重要。本文将深入探讨Android WiFi的模块程序、初始化过程、连接AP的步骤,以及WiFi SLAM...

    深入理解Android WiFi模块 NFC和GPS卷

    总结来说,本资料“深入理解Android WiFi模块 NFC和GPS卷”将涵盖这些关键领域的基本概念、API使用、以及实践应用案例,是初学者学习Android开发中不可或缺的一部分。通过阅读这份文档,你将能够建立起对这些技术的...

    android环境下wifi模块编程

    在Android环境下进行WiFi模块编程,主要是利用Android系统提供的API来操控设备的WiFi功能,包括开启/关闭WiFi,扫描可用的WiFi网络,连接指定的网络,以及处理WiFi状态变化等。以下将详细介绍相关知识点: 1. **...

    深入理解Android:WIFI模块 NFC和GPS卷

    《深入理解Android:WIFI模块 NFC和GPS卷》是一本专为Android开发者和爱好者准备的高级技术指南,旨在帮助读者全面掌握Android系统中无线通信、近场通信和定位服务的关键技术。这本书详细阐述了Android平台下WiFi、...

    android wifi 的大致流程图

    - 在Android WiFi模块中,部分操作需要与底层C/C++库进行交互,这时就会用到JNI(Java Native Interface)。例如,`WifiNative`类就是用来封装与原生层交互的逻辑。 - 例如加载内核模块、启动`wpa_supplicant`等操作...

    深入理解Android:WiFi模块 NFC和GPS卷 - 邓凡平-4

    《深入理解Android:WiFi模块 NFC和GPS卷》是邓凡平先生的一本深入解析Android系统中无线通信技术的专业书籍,主要涵盖了Android系统中WiFi、NFC(近场通信)和GPS(全球定位系统)这三个重要模块。这本书对于...

    STM32单片机通过ESP8266WiFi模块与Android APP实现数据传输软件源码.zip

    在这个项目中,STM32将扮演主控角色,负责收集数据并发送到ESP8266 WiFi模块,后者作为一个无线通信桥梁,将数据传输到Android应用程序。 ESP8266是一款经济实惠且功能强大的WiFi模块,它可以作为Wi-Fi网络的客户端...

    Android__WIFI模块分析

    本文将深入解析Android WIFI模块的架构、核心模块、工作流程以及相关代码实现。 **WIFI模块框图** WIFI模块的架构从上到下可以分为应用层、框架层、JNI层(Java Native Interface)和硬件层。在应用层,主要包括...

    深入理解Android:WiFi模块 NFC和GPS卷 - 邓凡平.zip

    《深入理解Android:WiFi模块 NFC和GPS卷》是由邓凡平编著的一本关于Android系统中关键无线技术的专业书籍。这本书主要聚焦于Android系统中WiFi、NFC(近场通信)和GPS(全球定位系统)这三大模块的原理、实现与应用...

    Wifi模块全总结.pdf

    WIFI模块的解析和启动流程涉及框架分析和启动流程,主要包括WIFI适配层的解析和Wifi启动流程。在此过程中,WIFI驱动流程分析和网络设备注册流程都是关键步骤。 电源管理在WIFI模块中也是一个重要的组成部分。电源...

    android wifi框架

    本文将基于Android 2.3版本,对WiFi模块进行深度解析,主要聚焦于关键文件的分析、`wpa_supplicant`的探讨以及WiFi启动流程的详解。 #### 关键文件解析:`WifiSettings.java` `packages/apps/Settings/src/...

    Android WIFI开发介绍

    #### 一、Android WIFI模块概述 Android系统中对于WIFI功能的支持主要依赖于一系列组件和服务的协同工作。从架构上看,这些组件和服务可以大致分为以下几个层次: 1. **应用层**: 包含用户可见的应用程序以及系统...

    android WIFI 总结

    对于希望深入了解Android WiFi模块工作原理的开发者来说,这篇文章提供了非常有价值的参考信息。 ### 无线保真技术简介 WIFI(Wireless Fidelity)是一种基于IEEE 802.11标准的无线局域网技术,它能够提供高达11...

    Android Wifi Driver Porting

    以下是对这一知识点的深入解析: ### Android Wi-Fi驱动移植详解 #### 1. 修改Build Target配置 在进行Wi-Fi驱动移植时,首先需要对Android源代码中的`build/target/board/generic/BoardConfig.mk`文件进行修改。...

    Android打开与关闭wifi源代码

    Android 中 Wi-Fi 的打开与关闭源代码解析 Android 作为一个流行的移动操作系统,Wi-Fi 连接是其核心功能之一。用户可以通过 Wi-Fi 连接到互联网,访问各种在线资源。在 Android 中,开发者可以通过 Wi-FiManager ...

    android wifi网络摄像头源代码

    《Android WiFi网络摄像头源代码解析》 在移动设备与物联网技术日益融合的今天,利用智能手机作为网络摄像头已不再是新鲜事。Android系统以其开放性和灵活性,为开发者提供了丰富的接口和工具来实现这一功能。本篇...

    Android-实现了Android设备之间通过Wifi传输文件的功能

    本文将详细解析如何利用Android的网络编程技术来构建这样的应用。 首先,我们要理解Android的网络编程基础。Android系统支持多种网络协议,如TCP/IP、HTTP、FTP等,这些协议为设备间的通信提供了基础。Wi-Fi文件...

    wifi模块控制小车的程序

    2. **固件编程**:为WiFi模块编写固件,使其能够接收和解析来自手机应用的指令,然后将其转化为可执行的动作。 3. **手机应用开发**:创建Android应用,设计用户友好的界面,用户可以在这个界面上直观地操作小车。...

Global site tag (gtag.js) - Google Analytics