Search code examples
androidkotlinandroid-wifi

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


i'm using Google guide to mediaPlayer. To lock wi-fi from being disabled it's recommended to lock it while playing media via wi-fi:

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

But since API 29 WIFI_MODE_FULL is deprecated. So how can i lock wi-fi on API 29 and above?

P.S. should we also lock mobile internet connection or it's always available?


Solution

  • There are some changes in Api 29 regarding Wi-Fi performance modes. According to the 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.

    To support Api 29 you can now use WIFI_MODE_FULL_LOW_LATENCY or WIFI_MODE_FULL_HIGH_PERF constants:

    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"
    )