Skip to content

Instantly share code, notes, and snippets.

@vladimirpetrovski
Last active March 27, 2020 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vladimirpetrovski/aec62d79225732fa9d554b4c5fc3d0c0 to your computer and use it in GitHub Desktop.
Save vladimirpetrovski/aec62d79225732fa9d554b4c5fc3d0c0 to your computer and use it in GitHub Desktop.
class WiFiConnectLegacyUseCase(private val context: Context) {
private var wifiManager =
context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
private val connectivityManager =
context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private val wifiSSID = "My Network"
private val wifiPassword = "password1234"
operator fun invoke(): Single<Network> {
return connect()
.delay(5, TimeUnit.SECONDS)
.timeout(20, TimeUnit.SECONDS)
.andThen(Single.defer { initNetwork() })
}
private fun connect(): Completable {
return Completable.create { emitter ->
val intentFilter = IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION)
val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (isConnectedToCorrectSSID()) {
Timber.v("Successfully connected to the device.")
emitter.onComplete()
} else {
Timber.w("Still not connected to ${wifiSSID}. Waiting a little bit more...")
}
}
}
Timber.v("Registering connection receiver...")
context.registerReceiver(receiver, intentFilter)
emitter.setCancellable {
Timber.v("Unregistering connection receiver...")
context.unregisterReceiver(receiver)
}
addNetwork(emitter)
}
}
private fun initNetwork(): Single<Network> {
Timber.v("Initializing network...")
return Single.just(connectivityManager.allNetworks.find {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
connectivityManager.getNetworkCapabilities(it)
.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
} else {
connectivityManager.getNetworkInfo(it).extraInfo == wifiSSID
}
})
}
private fun addNetwork(emitter: CompletableEmitter) {
Timber.v("Connecting to ${wifiSSID}...")
val wc = WifiConfiguration()
wc.SSID = "\"" + wifiSSID + "\""
wc.preSharedKey = "\"" + wifiPassword + "\""
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK)
val netId = wifiManager.addNetwork(wc)
if (netId != -1) {
if (!wifiManager.enableNetwork(netId, true)) {
Timber.e("Failed to connect to the device.")
emitter.tryOnError(IllegalArgumentException("Failed to connect to the device"))
}
} else {
Timber.e("Failed to connect to the device. addNetwork() returned -1")
emitter.tryOnError(IllegalArgumentException("Failed to connect to the device. addNetwork() returned -1"))
}
}
private fun isConnectedToCorrectSSID(): Boolean {
val currentSSID = wifiManager.connectionInfo.ssid ?: return false
Timber.v("Connected to $currentSSID")
return currentSSID == "\"${wifiSSID}\""
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment