API29如何设置wifi锁定模式?

How to set wi-fi in lock mode in API 29?

我正在使用 Google mediaPlayer 指南。要锁定 wi-fi 不被禁用,建议在通过 wi-fi 播放媒体时将其锁定:

val wifiManager = getSystemService(Context.WIFI_SERVICE) as WifiManager
val wifiLock: WifiManager.WifiLock =
    wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock")

但由于 API 29 WIFI_MODE_FULL 已弃用。那么如何在 API 29 及更高版本上锁定 Wi-Fi?

P.S。我们还应该锁定移动互联网连接还是始终可用?

Api29 在 Wi-Fi 性能模式 方面有一些变化。根据 Android 10 highlights documentation:

Apps can now request adaptive Wi-Fi by enabling high performance and low latency modes. These can be a great benefit where low latency is important to the user experience, such as real-time gaming, active voice calls, and similar use-cases. The platform works with the device firmware to meet the requirement with the lowest power consumption. To use the new performance modes, call WifiManager.WifiLock.createWifiLock() with WIFI_MODE_FULL_LOW_LATENCY or WIFI_MODE_FULL_HIGH_PERF. In these modes, the platform works with the device firmware to meet the requirement with lowest power consumption.

为了支持 Api 29,您现在可以使用 WIFI_MODE_FULL_LOW_LATENCY or WIFI_MODE_FULL_HIGH_PERF 常量:

val wifiManager = getSystemService(Context.WIFI_SERVICE) as WifiManager
val wifiLock: WifiManager.WifiLock = wifiManager.createWifiLock(
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) WifiManager.WIFI_MODE_FULL_LOW_LATENCY 
    else WifiManager.WIFI_MODE_FULL, 
    "mylock"
)