Android / Connect Wifi on my app
2018-04-13
Prerequsites
Env.
- Android studio 3
- Target API 26
- Kotlin
Getting Started
1. Permission
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
2. Code
kotlin
fun wifiConnect() {
val ssid = "my hotspot ssid"
val key = "my hotspot password"
val wifiConfig = WifiConfiguration()
wifiConfig.SSID = "\"" + ssid + "\""
wifiConfig.preSharedKey = "\"" + key + "\""
wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK)
val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
val netId = wifiManager.addNetwork(wifiConfig)
wifiManager.disconnect()
wifiManager.enableNetwork(netId, true)
wifiManager.reconnect()
}