Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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)
- }
Add Comment
Please, Sign In to add comment