Skip to content

Instantly share code, notes, and snippets.

@Astroa7m
Last active June 29, 2022 17:17
Show Gist options
  • Save Astroa7m/802731edcabe09df95f72132eb96a110 to your computer and use it in GitHub Desktop.
Save Astroa7m/802731edcabe09df95f72132eb96a110 to your computer and use it in GitHub Desktop.
@RequiresApi(Build.VERSION_CODES.Q)
fun connect29AndAbove(ssid: String, passPhrase: String) {
if (!wifiManager.isWifiEnabled) {
Toast.makeText(this, "Wifi is disabled please enable it to proceed", Toast.LENGTH_SHORT).show()
val panelIntent = Intent(Settings.Panel.ACTION_WIFI)
launcher.launch(panelIntent)
}
val suggestion = WifiNetworkSuggestion.Builder()
.setSsid(ssid)
.setWpa2Passphrase(passPhrase)
.setIsAppInteractionRequired(true)
.build()
wifiManager.removeNetworkSuggestions(listOf(suggestion))
wifiManager.addNetworkSuggestions(listOf(suggestion))
val intentFilter = IntentFilter(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION)
val broadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (!intent.action.equals(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION)) {
return
}
}
}
this.registerReceiver(broadcastReceiver, intentFilter)
hasScanned = false
}
@SuppressLint("MissingPermission")
fun connectBelow29(ssid: String, passPhrase: String) {
if (!wifiManager.isWifiEnabled) {
Toast.makeText(this, "Enabling wifi...", Toast.LENGTH_SHORT).show()
wifiManager.isWifiEnabled = true
}
val conf = WifiConfiguration()
conf.SSID = String.format("\"%s\"", ssid)
conf.preSharedKey = String.format("\"%s\"", passPhrase)
wifiManager.addNetwork(conf)
val netId = wifiManager.addNetwork(conf)
wifiManager.disconnect()
wifiManager.enableNetwork(netId, true)
wifiManager.reconnect()
Toast.makeText(this, "Connecting...", Toast.LENGTH_SHORT).show()
hasScanned = false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment