Skip to content

Instantly share code, notes, and snippets.

@jeffreydelooff
Last active July 15, 2021 12:18
Show Gist options
  • Save jeffreydelooff/6ec5cf48f191a19c14bda94fc50722f0 to your computer and use it in GitHub Desktop.
Save jeffreydelooff/6ec5cf48f191a19c14bda94fc50722f0 to your computer and use it in GitHub Desktop.
Android NetworkHelper to connect to WiFi
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()
}
}
}
}
}
@AhmedNawaz01
Copy link

Hi @jeffreydelooff
Is it working on your side?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment