1.先導入函示庫(build.gradle: Module)
dependencies {
implementation 'com.thanosfisherman.wifiutils:wifiutils:1.6.1'
}
2.添加權限
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
3.程式碼範例
a.詢問權限
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 666)
b.開啟Wifi
WifiUtils.withContext(applicationContext).enableWifi()
c.關閉Wifi
WifiUtils.withContext(applicationContext).disableWifi()
d.連線Wifi
WifiUtils.withContext(applicationContext)
.connectWith("SSID", "PASSWORD")
.setTimeout(15000)
.onConnectionResult(object : ConnectionSuccessListener {
override fun failed(errorCode: ConnectionErrorCode) {
Log.d("WifiUtils", errorCode.toString())
}
override fun success() {
Log.d("WifiUtils", "success")
}
}).start()
e.移除連線Wifi
WifiUtils.withContext(applicationContext)
.remove("SSID", object : RemoveSuccessListener {
override fun failed(errorCode: RemoveErrorCode) {
Log.d("WifiUtils", errorCode.toString())
}
override fun success() {
Log.d("WifiUtils", "success")
}
})
4.效果展示