Commit f5ab7f80 by patpat

WifiAction更换为kotlin

parent 9b942d2b
package com.bgycc.smartcanteen.action
import android.util.Log
import com.bgycc.smartcanteen.event.WifiStateEvent
import com.bgycc.smartcanteen.helper.TimerHelper
import com.bgycc.smartcanteen.helper.WifiHelpler
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject
class WifiAction private constructor() : Action(ActionEnum.CONFIG_WIFI.name) {
companion object {
private val TAG = WifiAction::class.java.simpleName
private var sDefault: WifiAction? = null
@Synchronized fun getDefault(): WifiAction {
if (sDefault == null) {
sDefault = WifiAction()
}
return sDefault!!
}
}
private fun fail() {
fail("")
TimerHelper.timeout({
state = State.INITED
EventBus.getDefault().post(WifiStateEvent(-1))
}, 3000)
}
fun exec(data: JSONObject) {
if (state != State.INITED) return
state = State.STARTED
try {
val ssid = data.getString("ssid")
val pwd = data.getString("pwd")
val type = data.optString("type", "wpa")
val identity = data.optString("identity")
WifiHelpler.connect(ssid, identity, pwd, type)
EventBus.getDefault().post(WifiStateEvent(1, "正在启动Wifi"))
if (!WifiHelpler.setEnable(true)) {
EventBus.getDefault().post(WifiStateEvent(1, "无法启动Wifi"))
timeout({
state = State.INITED
EventBus.getDefault().post(WifiStateEvent(-1))
}, 3000)
return
}
EventBus.getDefault().post(WifiStateEvent(10, "正在配置Wifi"))
val config = WifiHelpler.createWifiConfiguration(ssid, identity, pwd, type)
if (config == null) {
EventBus.getDefault().post(WifiStateEvent(10, "Wifi参数有误"))
timeout({
state = State.INITED
EventBus.getDefault().post(WifiStateEvent(-1))
}, 3000)
return
}
try {
if (!WifiHelpler.removeWifiConfiguration(ssid)) throw Exception("无法修改Wifi配置")
val netId = WifiHelpler.addNetwork(config)
if (!WifiHelpler.enableNetwork(netId)) throw Exception("无法应用Wifi配置")
} catch (e: Exception) {
EventBus.getDefault().post(WifiStateEvent(20, e.message))
timeout({
state = State.INITED
EventBus.getDefault().post(WifiStateEvent(-1))
}, 3000)
return
}
EventBus.getDefault().post(WifiStateEvent(30, "正在连接Wifi"))
TimerHelper.loop({ id, isLastTime ->
if (isLastTime) {
if (state == State.STARTED) {
state = State.FAIL
EventBus.getDefault().post(WifiStateEvent(30, "无法连接Wifi"))
timeout({
state = State.INITED
EventBus.getDefault().post(WifiStateEvent(-1))
}, 3000)
}
} else {
val info = WifiHelpler.getWifiInfo()
if (info != null) {
Log.i(TAG, "ip: " + info.ipAddress)
if (info.ipAddress != 0) {
state = State.SUCCESS
EventBus.getDefault().post(WifiStateEvent(30, "已连接Wifi"))
timeout({
state = State.INITED
EventBus.getDefault().post(WifiStateEvent(-1))
}, 3000)
return@loop false
}
}
}
return@loop true
}, 1000, 10)
} catch (e: Exception) {
}
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment