在我的应用程序中,我试图自动连接到特定的SSID(在Android Q中)。我使用“WifiNetworkSpecifier”,“NetworkRequest”和“ConnectivityManager”类来实现这一点。当我发出请求时,屏幕上会出现一个对话框,询问我是否连接到此SSID,我点击后就会连接。但是有两个问题:
- 它没有真正连接(没有互联网),我必须禁用和启用WiFi才能有机会真正连接!
- 当我从内存中清除应用程序时,它会自动断开连接。
fun connectToWifi(networkSSID: String, networkPassword: String?, bssid: String?)
val specifier = WifiNetworkSpecifier.Builder()
.setSsid(networkSSID)
if (networkPassword != null) {
specifier.setWpa2Passphrase(networkPassword)
}
if (bssid != null) {
specifier.setBssid(MacAddress.fromString(bssid))
}
val request = NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.setNetworkSpecifier(specifier.build())
.build()
val connectivityManager =
singletonArgument.context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network?) {
Log.d(TAG, "network available")
}
override fun onUnavailable() {
Log.d(TAG, "network unavailable")
}
}
connectivityManager.requestNetwork(request, networkCallback)
}