Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
class WiFiConnectUseCase(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"
@RequiresApi(api = Build.VERSION_CODES.Q)
operator fun invoke(): Single<Pair<Network, ConnectivityManager.NetworkCallback>> { //return the NetworkCallback in order to disconnect properly from the device
return connect()
.delay(3, TimeUnit.SECONDS) // wait for 3 sec, just to make sure everything is configured on the device
private fun connect(): Single<Pair<Network, ConnectivityManager.NetworkCallback>> {
return Single.create { emitter ->
val specifier = WifiNetworkSpecifier.Builder()
val networkRequest = NetworkRequest.Builder()
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) // as not internet connection is required for this device
val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
Timber.v("connect to WiFi success. Network is available.")
emitter.onSuccess(Pair(network, this))
override fun onUnavailable() {
Timber.w("connect to WiFi failed. Network is unavailable")
emitter.tryOnError(IllegalArgumentException("connect to WiFi failed. Network is unavailable"))
connectivityManager.requestNetwork(networkRequest, networkCallback)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.