Created
March 27, 2020 19:25
-
-
Save vladimirpetrovski/000d2bd7ecc7a9abe828a060cf8decbd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class WiFiDisconnectUseCase(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" | |
| operator fun invoke(networkCallback: ConnectivityManager.NetworkCallback? = null) { //we send the NetworkCallback as parameter from Android 10 and above | |
| if (wifiManager.connectionInfo.ssid != "\"$wifiSSID\"") { | |
| Timber.w("Skipping disconnect. The device is not connected to $wifiSSID.") | |
| return | |
| } | |
| networkCallback?.apply { | |
| Timber.v("unregistering network callback") | |
| connectivityManager.unregisterNetworkCallback(this) | |
| } | |
| val networkId = wifiManager.connectionInfo.networkId | |
| Timber.v("Disconnecting from ${wifiManager.connectionInfo.ssid}...") | |
| if (networkId != -1) { | |
| return if (!wifiManager.removeNetwork(networkId)) { | |
| Timber.e("Failed to remove network ${wifiSSID}.") | |
| } else { | |
| Timber.v("Successfully removed network ${wifiSSID}.") | |
| } | |
| } else { | |
| Timber.w("Cannot remove network with id -1") | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment