清单(声明和授予的权限)
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
主班
class MainActivity {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo = connectivityManager.activeNetwork
val capabilities = connectivityManager.getNetworkCapabilities(networkInfo)
if (capabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true) {
val wifiInfo = capabilities.transportInfo as WifiInfo
Log.d("DEBUG", "ssid: ${wifiInfo.ssid}")
}
val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
val connectionInfo = wifiManager.connectionInfo
Log.d("DEBUG", "ssid (deprecated) ${connectionInfo.ssid}")
}
输出
ssid: <unknown ssid>
ssid (deprecated): "bingo"
如何在针对最新 API 并使用最新的非弃用功能时检索 SSID?