くうと徒然なるままに

ゆるふわ を志向している なごやかです。

Android-Kotlin で Wifi のSSIDを取得する

class SSIDManager{
    fun GetSSID(ApplicationContext:Context): String{
        val wifiManager = ApplicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager

        if(!wifiManager.isWifiEnabled) return "";
        val connectInfo = wifiManager.connectionInfo

        val state = WifiInfo.getDetailedStateOf(connectInfo?.supplicantState)
        return when(state) {
            null -> ""
            NetworkInfo.DetailedState.CONNECTED, NetworkInfo.DetailedState.OBTAINING_IPADDR ->  wifiManager.connectionInfo.ssid
            else -> ""
        }
    }
}
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

実行結果

f:id:kuxumarin:20170802160708p:plain