Last active
July 15, 2021 12:18
-
-
Save jeffreydelooff/6ec5cf48f191a19c14bda94fc50722f0 to your computer and use it in GitHub Desktop.
Android NetworkHelper to connect to WiFi
This file contains 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 NetworkHelper @Inject constructor( | |
private val wifiManager: WifiManager | |
) { | |
fun connectToWifi(ssid: String, key: String) { | |
when { | |
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> { | |
// Remove possible conflicting network suggestions as we're not allowed to edit them | |
wifiManager.removeNetworkSuggestions( | |
listOf( | |
WifiNetworkSuggestion.Builder() | |
.setSsid(ssid) | |
.build() | |
) | |
) | |
// Add new network suggestion | |
wifiManager.addNetworkSuggestions( | |
listOf( | |
WifiNetworkSuggestion.Builder() | |
.setSsid(ssid) | |
.setWpa2Passphrase(key) | |
.build() | |
) | |
) | |
} | |
else -> { | |
val wifiConfig = WifiConfiguration().apply { | |
SSID = String.format("\"%s\"", ssid) | |
preSharedKey = String.format("\"%s\"", key) | |
} | |
with(wifiManager) { | |
val netId = addNetwork(wifiConfig) | |
disconnect() | |
enableNetwork(netId, true) | |
reconnect() | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @jeffreydelooff
Is it working on your side?