首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Android WiFiManager enableNetwork返回false

Android WiFiManager enableNetwork返回false
EN

Stack Overflow用户
提问于 2018-12-04 19:36:08
回答 1查看 3.1K关注 0票数 8

需要澄清:

代码中最有可能出现问题的部分是connect函数,您可以在代码块中找到它。

编辑:

我在LogCat中进行了很好的挖掘,发现了一些有趣的东西(这发生在enableNetwork被调用的那一刻):

代码语言:javascript
运行
复制
2018-12-04 20:13:14.508 1315-7000/? I/WifiService: enableNetwork uid=10158 disableOthers=true
2018-12-04 20:13:14.508 1315-1607/? D/WifiStateMachine: connectToUserSelectNetwork netId 49, uid 10158, forceReconnect = false
2018-12-04 20:13:14.541 1315-1607/? D/WifiConfigStore: Writing to stores completed in 14 ms.
2018-12-04 20:13:14.541 1315-1607/? E/WifiConfigManager: UID 10158 does not have permission to update configuration "SKYD7F55"WPA_PSK
2018-12-04 20:13:14.541 1315-1607/? I/WifiStateMachine: connectToUserSelectNetwork Allowing uid 10158 with insufficient permissions to connect=49

权限:

代码语言:javascript
运行
复制
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

我的任务是创建一个应用程序的一部分,用户将能够看到扫描的WiFi访问点(ScanResult)列表,能够选择一个,如果需要的话,可以显示一个进入PSK的屏幕。输入PSK后,系统将尝试连接到访问点,方法是首先创建和配置WifiConfig对象,使用addNetwork将配置添加到Wifi配置表,然后是disconnectenableNetworkreconnect (按顺序排列)。

我使用RX-Java2,以便能够链接网络设置的各个步骤。例如,disconnect方法返回一个Completable,如果WifiManager.disconnect()成功,该Completable将发出一个已完成的事件。这样做的方法是注册一个BroadcastReceiver以侦听NETWORK_STATE_CHANGED_ACTION,然后如果networkInfo extra有详细的状态DISCONNECTED,则发出一个完成事件。同样的逻辑也适用于connect()函数。

现在,addNetwork()成功了(所以我的WiFi配置函数是正确的),然后我使用andThenCompletable链接到连接Single。我在代码中放置了断点,可以看到一切都按正确的顺序运行,断开连接成功,然后它的广播接收器成功注册,但是enableNetwork()调用返回false (指示OS未能发出enableNetwork命令)。

我99%肯定这不是我如何使用RX的问题,但是,考虑到addNetworkdisconnect正在成功(表明我的wifi配置创建代码很好),我开始怀疑我的RX代码是否错了,或者,B)我的WiFi配置创建是错误的。

因此,我将发布下面的所有代码以及用例,并将非常感谢任何建议。

Emitters.kt:

代码语言:javascript
运行
复制
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.NetworkInfo
import android.net.wifi.SupplicantState
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import com.google.common.base.Optional
import io.reactivex.*
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import java.lang.Exception

private const val TAG = "Emitters"
private const val SIGNAL_STRENGTH_RANGE = 4

/**
 * Use case of these emitters (in presenter or interactor):
 *
 * // If network is open, then go ahead and connect to it, else show enter password form
 * isNetworkOpen(context, scanResult).flatMapCompletable { isNetworkOpen ->
 *     if (isNetworkOpen) {
 *         connectToOpenWifi(context, scanResult.ssid, scanResult.bssid)
 *     } else {
 *         Completable.error(WifiException("The specified network requires a password")
 *     }
 * }.subscribeOn(Schedulers.io())
 *  .observeOn(AndroidSchedulers.mainThread())
 *  .subscribe({
 *      view?.showSuccessfullyConnected()
 *  }, { error ->
 *         when (error) {
 *             is WifiAuthException -> {
 *                  val auth = error.wifiScanResult.auth
 *                  val keyManagement = error.wifiScanResult.keyManagement
 *                  val security = "$auth/$keyManagement"
 *                  viewStateStack.add(NetworkSummaryViewState(error.wifiScanResult, security))
 *                  switchToViewState(viewStateStack.peek())
 *              } else -> {
 *                  viewStateStack.add(FailedToConnectViewState(networkName))
 *                  switchToViewState(viewStateStack.peek())
 *              }
 *          }
 *      }
 *  })
 *
 *  // Called by view to connect to closed network with provided password
 *  connectToClosedWifi(context, scanResult, password)
 *  .subscribeOn(Schedulers.io())
 *  .observeOn(AndroidSchedulers.mainThread())
 *  .subscribe({
 *      view?.showSuccessfullyConnected()
 *  }, { error ->
 *      view?.showFailedToConnect()
 *  })
 */

/**
 * Creates a Flowable that emits WiFiScanResults
 */
fun wifiScanResults(context: Context): Flowable<Set<WiFiScanResult>> = Flowable.create<Set<WiFiScanResult>> ({ emitter ->
    val wifiManagerWrapper = WifiManagerWrapper(context.applicationContext)

    if (!wifiManagerWrapper.wifiManager.isWifiEnabled && !wifiManagerWrapper.wifiManager.setWifiEnabled(true)) {
        wifiManagerWrapper.dispose()
        emitter.onError(WiFiException("WiFi not enabled and couldn't enable it"))
        return@create
    }

    // Broadcast receiver that handles wifi scan results
    val wifiScanReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action == WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) {
                val scanResults = wifiManagerWrapper.wifiManager.scanResults

                if (scanResults !== null) {
                    emitter.onNext(scanResults.map { scanResult ->
                        val signalStrength = WifiManager.calculateSignalLevel(scanResult.level, SIGNAL_STRENGTH_RANGE)

                        val capabilities = scanResult.capabilities.substring(1, scanResult.capabilities.indexOf(']') -1)
                            .split('-')
                            .toSet()

                        WiFiScanResult(scanResult.SSID,
                            scanResult.BSSID,
                            capabilities.elementAtOrNull(0) ?: "",
                            capabilities.elementAtOrNull(1) ?: "",
                            capabilities.elementAtOrNull(2) ?: "",
                            signalStrength)

                    }.toSet())
                }
            }

            if (!wifiManagerWrapper.wifiManager.startScan()) {
                emitter.onError(WiFiException("WiFi not enabled"))
            }
        }
    }

    val wifiScanResultsIntentFilter = IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
    context.applicationContext.registerReceiver(wifiScanReceiver, wifiScanResultsIntentFilter)

    emitter.setCancellable {
        context.unregisterReceiver(wifiScanReceiver)
        wifiManagerWrapper.dispose()
    }

    if (!wifiManagerWrapper.wifiManager.startScan()) {
        emitter.onError(WiFiException("WiFi not enabled"))
    }
}, BackpressureStrategy.LATEST).subscribeOn(Schedulers.io())

/**
 * Returns a single indicating if the [scanResult] is open
 */
fun isNetworkOpen(context: Context,
                  scanResult: WiFiScanResult): Single<Boolean> = Single.create<Boolean> { emitter ->
    val wifiManagerWrapper = WifiManagerWrapper(context.applicationContext)

    emitter.setCancellable {
        wifiManagerWrapper.dispose()
    }

    if (scanResult.auth.contains("WEP")) {
        emitter.onSuccess(true)
    } else {
        emitter.onSuccess(false)
    }
}

/**
 * Attempts to connect to an open wifi access point specified by [scanResult]
 * Emits a completed event if successful, else emits an error
 */
fun connectToOpenWifi(context: Context,
                      scanResult: WiFiScanResult): Completable = Completable.create { emitter ->
    val ssid = scanResult.ssid
    val bssid = scanResult.bssid

    val wifiManagerWrappper = WifiManagerWrapper(context.applicationContext)

    if (!wifiManagerWrappper.wifiManager.isWifiEnabled && !wifiManagerWrappper.wifiManager.setWifiEnabled(true)) {
        wifiManagerWrappper.dispose()
        emitter.onError(WiFiException("Wifi not enabled"))
    }

    val updateWifiStateObs = getExistingConfiguration(wifiManagerWrappper.wifiManager, ssid, bssid).flatMap { existingConfig ->
        if (!existingConfig.isPresent) {
            createOpenWifiConfiguration(scanResult).flatMap { wifiConfig ->
                val newNetworkId = wifiManagerWrappper.wifiManager.addNetwork(wifiConfig)
                if (newNetworkId < 0)
                    throw WiFiException("Failed to add new access point ${scanResult.ssid}")

                val currentWifiConnection = wifiManagerWrappper.wifiManager.connectionInfo

                if (currentWifiConnection !== null) {
                    disconnect(context, wifiManagerWrappper.wifiManager).andThen(
                        connect(context, wifiManagerWrappper.wifiManager, wifiConfig.SSID, newNetworkId)
                    )
                } else {
                    connect(context, wifiManagerWrappper.wifiManager, wifiConfig.SSID, newNetworkId)
                }
            }
        } else {
            Single.just(existingConfig.get())
        }
    }

    val compositeDisposable = CompositeDisposable()

    emitter.setCancellable {
        compositeDisposable.clear()
        wifiManagerWrappper.dispose()
    }

    try {
        compositeDisposable.add(updateWifiStateObs.subscribe({
            emitter.onComplete()
        }, { error ->
            emitter.onError(error)
        }))
    } catch (ex: Exception) {
        compositeDisposable.clear()
        wifiManagerWrappper.dispose()
        emitter.onError(ex)
    }
}

/**
 * Attempts to connect to an closed [scanResult] by providing the given [preSharedKey]
 * Emits a completed event if successful, else emits an error
 */
fun connectToClosedWifi(context: Context,
                        scanResult: WiFiScanResult,
                        preSharedKey: String): Completable = Completable.create { emitter ->
    val ssid = scanResult.ssid
    val bssid = scanResult.bssid

    val wifiManagerWrappper = WifiManagerWrapper(context.applicationContext)

    if (!wifiManagerWrappper.wifiManager.isWifiEnabled && !wifiManagerWrappper.wifiManager.setWifiEnabled(true)) {
        wifiManagerWrappper.dispose()
        emitter.onError(WiFiException("Wifi not enabled"))
    }

    val updateWifiStateObs =
        getExistingConfiguration(wifiManagerWrappper.wifiManager, ssid, bssid).flatMap { existingConfig ->
            if (!existingConfig.isPresent) {
                createClosedWifiConfiguaration(scanResult, preSharedKey).flatMap { wifiConfig ->
                    val newNetworkId = wifiManagerWrappper.wifiManager.addNetwork(wifiConfig)
                    if (newNetworkId < 0)
                        throw WiFiException("Failed to add new access point ${scanResult.ssid}")

                    val currentWifiConnection = wifiManagerWrappper.wifiManager.connectionInfo

                    if (currentWifiConnection !== null) {
                        disconnect(context, wifiManagerWrappper.wifiManager).andThen(
                            connect(context, wifiManagerWrappper.wifiManager, wifiConfig.SSID, newNetworkId)
                        )
                    } else {
                        connect(context, wifiManagerWrappper.wifiManager, wifiConfig.SSID, newNetworkId)
                    }
                }
            } else {
                Single.just(existingConfig.get())
            }
        }

    val compositeDisposable = CompositeDisposable()

    emitter.setCancellable {
        compositeDisposable.clear()
        wifiManagerWrappper.dispose()
    }

    try {
        compositeDisposable.add(updateWifiStateObs.subscribe({
            emitter.onComplete()
        }, { error ->
            emitter.onError(error)
        }))
    } catch (ex: Exception) {
        compositeDisposable.clear()
        wifiManagerWrappper.dispose()
        emitter.onError(ex)
    }
}

/**
 * Wrapper class for WiFiManager that creates a multicast lock to make the app handle multicast wifi packets
 * Handles disposing of the lock and cleaning up of resources via the dispose method
 */
private class WifiManagerWrapper(context: Context) {
    val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE)
            as? WifiManager ?: throw IllegalStateException("Could not get system Context.WIFI_SERVICE")

    // Create and acquire a multicast lock to start receiving multicast wifi packets
    private var lock = wifiManager.createMulticastLock(TAG + "_lock").apply {
        acquire()
    }

    // Dispose of the lock
    fun dispose() {
        if (lock.isHeld) {
            try {
                lock.release()
            } catch (ignore: Exception) {
                EventReporter.i(TAG, "Failed to release lock on wifi manager wrapper")
            }
            lock = null
        }
    }
}

/**
 * Disconnects from the connected wifi network and emits a completed event if no errors occurred
 */
private fun disconnect(context: Context,
                       wifiManager: WifiManager) = Completable.create { emitter ->

    val wifiDisconnectionReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action == WifiManager.NETWORK_STATE_CHANGED_ACTION) {
                val networkInfo = intent.getParcelableExtra<NetworkInfo>(WifiManager.EXTRA_NETWORK_INFO) ?: return
                if (networkInfo.detailedState == NetworkInfo.DetailedState.DISCONNECTED) {
                    context.applicationContext.unregisterReceiver(this)
                    emitter.onComplete()
                }
            }
        }
    }

    val networkStateChangedFilter = IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION)

    context.applicationContext.registerReceiver(wifiDisconnectionReceiver, networkStateChangedFilter)

    emitter.setCancellable {
        if (!emitter.isDisposed)
            context.applicationContext.unregisterReceiver(wifiDisconnectionReceiver)
    }

    if (!wifiManager.disconnect())
        emitter.onError(WiFiException("Failed to issue disconnect command to wifi subsystem"))
}

/**
 * Connects to the wifi access point at specified [ssid] with specified [networkId]
 * And returns the [WifiInfo] of the network that has been connected to
 */
private fun connect(context: Context,
                    wifiManager: WifiManager,
                    ssid: String,
                    networkId: Int) = Single.create<WifiInfo> { emitter ->

    val wifiConnectionReceiver = object : BroadcastReceiver() {
        var oldSupplicantState: SupplicantState? = null

        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action == WifiManager.NETWORK_STATE_CHANGED_ACTION) {
                val networkInfo = intent.getParcelableExtra<NetworkInfo>(WifiManager.EXTRA_NETWORK_INFO) ?: return

                if (networkInfo.detailedState == NetworkInfo.DetailedState.DISCONNECTED) {
                    context.applicationContext.unregisterReceiver(this)
                    emitter.onError(WiFiException("Failed to connect to wifi network"))
                }
                else if (networkInfo.detailedState == NetworkInfo.DetailedState.CONNECTED) {
                    val wifiInfo = intent.getParcelableExtra<WifiInfo>(WifiManager.EXTRA_WIFI_INFO) ?: return
                    if (ssid == wifiInfo.ssid.unescape()) {
                        context.applicationContext.unregisterReceiver(this)
                        emitter.onSuccess(wifiInfo)
                    }
                }
            } else if (intent.action == WifiManager.SUPPLICANT_STATE_CHANGED_ACTION) {
                val supplicantState = intent.getParcelableExtra<SupplicantState>(WifiManager.EXTRA_NEW_STATE)
                val oldSupplicantState = this.oldSupplicantState
                this.oldSupplicantState = supplicantState

                if (supplicantState == SupplicantState.DISCONNECTED) {
                    if (oldSupplicantState == null || oldSupplicantState == SupplicantState.COMPLETED) {
                        return
                    }
                    val possibleError = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, -1)
                    if (possibleError == WifiManager.ERROR_AUTHENTICATING) {
                        context.applicationContext.unregisterReceiver(this)
                        emitter.onError(WiFiException("Wifi authentication failed"))
                    }
                } else if (supplicantState == SupplicantState.SCANNING && oldSupplicantState == SupplicantState.DISCONNECTED) {
                    context.applicationContext.unregisterReceiver(this)
                    emitter.onError(WiFiException("Failed to connect to wifi network"))
                }
            }
        }
    }

    val networkStateChangedFilter = IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION)
    networkStateChangedFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)

    context.applicationContext.registerReceiver(wifiConnectionReceiver, networkStateChangedFilter)

    emitter.setCancellable {
        if (!emitter.isDisposed)
            context.applicationContext.unregisterReceiver(wifiConnectionReceiver)
    }

    wifiManager.enableNetwork(networkId, true)
    wifiManager.reconnect()
}

/**
 * Returns a Single, wrapping an Optional.absent if no existing configuration exists with the passed [ssid] and [bssid], else the found [WifiConfiguration]
  */
private fun getExistingConfiguration(wifiManager: WifiManager,
                                     ssid: String,
                                     bssid: String) = Single.create<Optional<WifiConfiguration>> { emitter ->
    val configuredNetworks = wifiManager.configuredNetworks
    if (configuredNetworks.isEmpty()) {
        emitter.onSuccess(Optional.absent())
    }
    emitter.onSuccess(Optional.fromNullable(configuredNetworks.firstOrNull { configuredNetwork ->
        configuredNetwork.SSID.unescape() == ssid && configuredNetwork.BSSID == bssid
    }))
}

/**
 * Emits a single of the open [WifiConfiguration] created from the passed [scanResult]
 */
private fun createOpenWifiConfiguration(scanResult: WiFiScanResult) = Single.fromCallable<WifiConfiguration> {
    val auth = scanResult.auth
    val keyManagement = scanResult.keyManagement
    val pairwiseCipher = scanResult.pairwiseCipher

    val config = WifiConfiguration()
    config.SSID = "\"" +  scanResult.ssid + "\""
    config.BSSID = scanResult.bssid

    var allowedProtocols = 0
    when {
        auth.isEmpty() -> {
            allowedProtocols = allowedProtocols or WifiConfiguration.Protocol.RSN
            allowedProtocols = allowedProtocols or WifiConfiguration.Protocol.WPA
        }
        auth.contains("WPA2") -> allowedProtocols = allowedProtocols or WifiConfiguration.Protocol.RSN
        auth.contains("WPA") -> {
            allowedProtocols = allowedProtocols or WifiConfiguration.Protocol.WPA
            allowedProtocols = allowedProtocols or WifiConfiguration.Protocol.RSN
        }
    }

    config.allowedProtocols.set(allowedProtocols)

    var allowedAuthAlgos = 0
    when {
        auth.contains("EAP") -> allowedAuthAlgos = allowedAuthAlgos or WifiConfiguration.AuthAlgorithm.LEAP
        auth.contains("WPA") -> allowedAuthAlgos = allowedAuthAlgos or WifiConfiguration.AuthAlgorithm.OPEN
        auth.contains("WEP") -> allowedAuthAlgos = allowedAuthAlgos or WifiConfiguration.AuthAlgorithm.SHARED
    }

    config.allowedAuthAlgorithms.set(allowedAuthAlgos)

    var allowedKeyManagers = WifiConfiguration.KeyMgmt.NONE
    if (keyManagement.contains("IEEE802.1X"))
        allowedKeyManagers = allowedKeyManagers or WifiConfiguration.KeyMgmt.IEEE8021X
    else if (auth.contains("WPA") && keyManagement.contains("EAP"))
        allowedKeyManagers = allowedKeyManagers or WifiConfiguration.KeyMgmt.WPA_EAP
    else if (auth.contains("WPA") && keyManagement.contains("PSK"))
        allowedKeyManagers = allowedKeyManagers or WifiConfiguration.KeyMgmt.WPA_PSK

    config.allowedKeyManagement.set(allowedKeyManagers)

    var allowedPairWiseCiphers = WifiConfiguration.PairwiseCipher.NONE
    if (pairwiseCipher.contains("CCMP"))
        allowedPairWiseCiphers = allowedPairWiseCiphers or WifiConfiguration.PairwiseCipher.CCMP
    if (pairwiseCipher.contains("TKIP"))
        allowedPairWiseCiphers = allowedPairWiseCiphers or WifiConfiguration.PairwiseCipher.TKIP

    config.allowedPairwiseCiphers.set(allowedPairWiseCiphers)

    config
}

/**
 * Emits a single of the closed [WifiConfiguration] created from the passed [scanResult] and [preSharedKey]
 * Or, emits an error signalling the [preSharedKey] was empty
 */
private fun createClosedWifiConfiguaration(scanResult: WiFiScanResult, preSharedKey: String) = Single.fromCallable<WifiConfiguration> {
    val auth = scanResult.auth
    val keyManagement = scanResult.keyManagement
    val pairwiseCipher = scanResult.pairwiseCipher

    val config = WifiConfiguration()
    config.SSID = "\"" +  scanResult.ssid + "\""
    config.BSSID = scanResult.bssid

    var allowedProtocols = 0
    when {
        auth.isEmpty() -> {
            allowedProtocols = allowedProtocols or WifiConfiguration.Protocol.RSN
            allowedProtocols = allowedProtocols or WifiConfiguration.Protocol.WPA
        }
        auth.contains("WPA2") -> allowedProtocols = allowedProtocols or WifiConfiguration.Protocol.RSN
        auth.contains("WPA") -> {
            allowedProtocols = allowedProtocols or WifiConfiguration.Protocol.WPA
            allowedProtocols = allowedProtocols or WifiConfiguration.Protocol.RSN
        }
    }

    config.allowedProtocols.set(allowedProtocols)

    var allowedAuthAlgos = 0
    when {
        auth.contains("EAP") -> allowedAuthAlgos = allowedAuthAlgos or WifiConfiguration.AuthAlgorithm.LEAP
        auth.contains("WPA") || auth.contains("WPA2") -> allowedAuthAlgos = allowedAuthAlgos or WifiConfiguration.AuthAlgorithm.OPEN
        auth.contains("WEP") -> allowedAuthAlgos = allowedAuthAlgos or WifiConfiguration.AuthAlgorithm.SHARED
    }

    config.allowedAuthAlgorithms.set(allowedAuthAlgos)

    var allowedKeyManagers = WifiConfiguration.KeyMgmt.NONE
    if (keyManagement.contains("IEEE802.1X"))
        allowedKeyManagers = allowedKeyManagers or WifiConfiguration.KeyMgmt.IEEE8021X
    else if (auth.contains("WPA") && keyManagement.contains("EAP"))
        allowedKeyManagers = allowedKeyManagers or WifiConfiguration.KeyMgmt.WPA_EAP
    else if (auth.contains("WPA") && keyManagement.contains("PSK"))
        allowedKeyManagers = allowedKeyManagers or WifiConfiguration.KeyMgmt.WPA_PSK
    else if (preSharedKey.isNotEmpty())
        allowedKeyManagers = allowedKeyManagers or WifiConfiguration.KeyMgmt.WPA_PSK
    else if (preSharedKey.isEmpty())
        allowedKeyManagers = allowedAuthAlgos or WifiConfiguration.KeyMgmt.WPA_PSK

    config.allowedKeyManagement.set(allowedKeyManagers)

    var allowedPairWiseCiphers = WifiConfiguration.PairwiseCipher.NONE
    if (pairwiseCipher.contains("CCMP"))
        allowedPairWiseCiphers = allowedPairWiseCiphers or WifiConfiguration.PairwiseCipher.CCMP
    if (pairwiseCipher.contains("TKIP"))
        allowedPairWiseCiphers = allowedPairWiseCiphers or WifiConfiguration.PairwiseCipher.TKIP

    config.allowedPairwiseCiphers.set(allowedPairWiseCiphers)

    if (preSharedKey.isNotEmpty()) {
        if (auth.contains("WEP")) {
            if (preSharedKey.matches("\\p{XDigit}+".toRegex())) {
                config.wepKeys[0] = preSharedKey
            } else {
                config.wepKeys[0] = "\"" + preSharedKey + "\""
            }
            config.wepTxKeyIndex = 0
        } else {
            config.preSharedKey = "\"" + preSharedKey + "\""
        }
    }

    config
}

/**
 * Extension function to remove escaped " from a string
 */
private fun String.unescape() =
    if (this.startsWith("\""))
        this.replace("\"", "")
    else
        this
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-12 18:32:07

好的,我终于明白了这一点,我希望我的答案能为将来遇到类似问题的人提供一些启示,因为这是令人讨厌的,也让我非常头疼。

造成这个问题的根本原因是我错误地配置了WiFiConfig对象,该对象是通过WiFiConfig表通过WiFiConfigManager.addNetwork()注册的。

我对WifiConfigManager.addNetwork()的合同做了大量的假设。我假设如果操作成功(即不返回-1),则正确配置传递的WiFiConfig。这个假设是错误的,我正在创建的allowedAuthAlgorithmsallowedProtocolsallowedKeyManagersallowedPairwiseCipher BitSet都是不正确的,但是对addNetwork()的调用成功了。我认为这是因为对addNetwork()的调用实际上只做了验证配置对于放在WiFiConfig表中是有效的,这与验证它是否是给定WiFi访问点的正确配置完全不同。这是由addNetwork()源代码中的注释备份的,这些注释没有像许多其他WiFiManager函数那样声明异步状态的传递,这表明(至少对我来说)操作系统没有试图通过调用addNetwork()来与访问点通信。

由于一位同事提出了一个非常有用的建议,即通过操作系统连接到所讨论的访问点,然后比较为该访问点创建的OS创建的WiFiConfig对象和由我自己的代码生成的用于差异的访问点,因此我注意到我的WiFiConfig配置不正确。在此之后不久,我才解决了原来的问题。

现在,为什么我的WiFiConfig对象被错误地创建了?这是因为我对如何配置WiFi (即所有协议、算法和密钥管理器背后的各种术语和含义)知之甚少。因此,在阅读了官方文档而没有收集到很多有用的信息之后,我转向StackOverflow问答,找到了一种正确设置WiFiConfig的反复模式,他们似乎都使用BitWise操作符创建了一个Int值,最终传递给了WiFiConfig.allowedProtocols.set()WiFiConfig.allowedPairwiseCiphers.set()WiFiConfig.allowedKeyManagement.set()WiFiConfig.allowedAuthAlgorithm.set()函数。

结果表明,每个配置选项的底层BitSet都是一种数据结构,它维护位的动态调整向量,其中WiFiConfig对象中给定BitSet实例中的位索引与WiFiConfig对象内隐式关联的String数组中的元素索引隐式对应。因此,如果希望提供多个protocolskeyManagementspairwiseCiphersauthAlgorithms,则需要在底层对应的BitSet上调用set,传递与匹配所选协议的隐式关联字符串数组的元素对应的正确索引。

在重写了我的WiFiConfig创建代码之后,这个问题自行解决了。虽然我的代码在最初的文章中有一个错误,但它也被修复了。

下面是新的WiFiConfig创建代码:

代码语言:javascript
运行
复制
/**
 * Emits a single of the [WifiConfiguration] created from the passed [scanResult] and [preSharedKey]
 */
private fun createWifiConfiguration(scanResult: WiFiScanResult, preSharedKey: String) = Single.fromCallable<WifiConfiguration> {
    val auth = scanResult.auth
    val keyManagement = scanResult.keyManagement
    val pairwiseCipher = scanResult.pairwiseCipher

    val config = WifiConfiguration()
    config.SSID = "\"" +  scanResult.ssid + "\""
    config.BSSID = scanResult.bssid

    if (auth.contains("WPA") || auth.contains("WPA2")) {
        config.allowedProtocols.set(WifiConfiguration.Protocol.WPA)
        config.allowedProtocols.set(WifiConfiguration.Protocol.RSN)
    }

    if (auth.contains("EAP"))
        config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.LEAP)
    else if (auth.contains("WPA") || auth.contains("WPA2"))
        config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN)
    else if (auth.contains("WEP"))
        config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED)

    if (keyManagement.contains("IEEE802.1X"))
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X)
    else if (auth.contains("WPA") && keyManagement.contains("EAP"))
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP)
    else if (auth.contains("WPA") && keyManagement.contains("PSK"))
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK)
    else if (auth.contains("WPA2") && keyManagement.contains("PSK"))
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK)

    if (pairwiseCipher.contains("CCMP") || pairwiseCipher.contains("TKIP")) {
        config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP)
        config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP)
    }

    if (preSharedKey.isNotEmpty()) {
        if (auth.contains("WEP")) {
            if (preSharedKey.matches("\\p{XDigit}+".toRegex())) {
                config.wepKeys[0] = preSharedKey
            } else {
                config.wepKeys[0] = "\"" + preSharedKey + "\""
            }
            config.wepTxKeyIndex = 0
        } else {
            config.preSharedKey = "\"" + preSharedKey + "\""
        }
    }

    config
}

下面是新的连接代码:

代码语言:javascript
运行
复制
/**
 * Connects to the wifi access point at specified [ssid] with specified [networkId]
 * And returns the [WifiInfo] of the network that has been connected to
 */
private fun connect(context: Context,
                    wifiManager: WifiManager,
                    ssid: String,
                    networkId: Int) = Single.create<WifiInfo> { emitter ->

    val wifiConnectionReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action == WifiManager.NETWORK_STATE_CHANGED_ACTION) {
                val networkInfo = intent.getParcelableExtra<NetworkInfo>(WifiManager.EXTRA_NETWORK_INFO) ?: return

                if (networkInfo.detailedState == NetworkInfo.DetailedState.CONNECTED) {
                    val wifiInfo = intent.getParcelableExtra<WifiInfo>(WifiManager.EXTRA_WIFI_INFO) ?: return
                    if (ssid.unescape() == wifiInfo.ssid.unescape()) {
                        context.applicationContext.unregisterReceiver(this)
                        emitter.onSuccess(wifiInfo)
                    }
                }
            }
        }
    }

    val networkStateChangedFilter = IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION)
    networkStateChangedFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)

    context.applicationContext.registerReceiver(wifiConnectionReceiver, networkStateChangedFilter)

    emitter.setCancellable {
        if (!emitter.isDisposed)
            context.applicationContext.unregisterReceiver(wifiConnectionReceiver)
    }

    wifiManager.enableNetwork(networkId, true)
}
票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53620234

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档