How to enable/disable WiFi from an application?

后端 未结 6 2170
说谎
说谎 2020-12-02 15:31

I want to enable/disable wifi from my Android application. How can I do that?

6条回答
  •  星月不相逢
    2020-12-02 16:18

    To enable/disable wifi from an app in Android Q (Android 10) use Settings Panel:

    val panelIntent = Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY)
    startActivityForResult(panelIntent, 0)
    

    On previous versions of Android this should work (appropriate permissions should be added to AndroidManifest file, see answers above):

    (context?.getSystemService(Context.WIFI_SERVICE) as? WifiManager)?.apply { isWifiEnabled = true /*or false*/ }
    

    Resulting code might look something like this:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val panelIntent = Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY)
        startActivityForResult(panelIntent, 0)
    } else {
        (context?.getSystemService(Context.WIFI_SERVICE) as? WifiManager)?.apply { isWifiEnabled = true /*or false*/ }
    }
    

    Where context is a reference to android.content.Context object.

提交回复
热议问题