Search code examples
androidandroid-wifi

Android - Programatically close the Wi-Fi dialog/panel


Android 29 has dropped the ability to programatically enable/disable the phone's Wi-Fi interface. An application I work on connects to an external wi-fi device (p2p, no outbound internet) programatically. If wi-fi is not enabled, we ask the user to enable it. There is a new system UI Panel API documented here. We can show a basic toggle switch to the user to enable wi-fi via this:

startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));

Once Wi-Fi is enabled we connect via the process described below:

Eg:

val ssid = ssidObtainedExternally()
val psk = pskObtainedExternally()
val specifier = WifiNetworkSpecifier.Builder()
.setSsid(ssid)
.setWpa2Passphrase(psk)
.build()

val request = NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.setNetworkSpecifier(specifier)
.build()

connectivityManager.requestNetwork(request, networkCallback)

However, one issue with this is that after the user switches the toggle to enabled, the same dialog will then start showing a list of available Wi-Fi networks which may entice the customer to choose the wi-fi device (since the SSID is just the name of the device, which they know). Since we will programmatically connect, we don't want the user to try and manually select the wi-fi network since they won't know the PSK. It would be ideal to dismiss the dialog as soon as they toggle the switch to enable.

I tested this with the GoPro 8 and that app seems to have a mechanism to dismiss the dialog once the user toggles the switch.

I've tried a few things so far with no luck. I tried using Application.registerActivityLifecycleCallbacks but it doesn't pick up the settings panel being created, started, or resumed.

I also tried the tip here: https://stackoverflow.com/a/32929066/94557 With no luck (the only visible activities were ones declared in my app that were in the stack)

Any ideas?


Solution

  • It looks like I've found a hack that seems to work and is probably what the gopro app does. The idea is to keep a reference to your current activity after you launch the Wifi settings panel. Once you detect that Wifi is enabled, call

       yourPreviousActivity.startActivity(yourPreviousActivityIntent) 
    

    with an intent that represents the screen you were on previously. You will want to add the following flag to the intent:

       FLAG_ACTIVITY_CLEAR_TOP
    

    The end result is your activity is re-launched and the settings panel is hidden. If you have any animation runs on open you will want to disable it.