Is it possible to add a network configuration on Android Q?

前端 未结 4 709
难免孤独
难免孤独 2021-01-02 00:42

Background

I\'ve noticed that in WifiManager class there is a function called addNetwork, that might be useful if I want to restore or save networks information (n

4条回答
  •  旧巷少年郎
    2021-01-02 00:58

    Looks like they've added support in Android 11(API 30) for adding network configuration that persists outside of the application scope and is saved as a system network configuration just like it was done with the deprecated WiFiManager method addNetwork. All you need to do is to use ACTION_WIFI_ADD_NETWORKS to show a system dialog that asks a user if he wants to proceed with adding a new Wifi suggestion to the system. This is how we start that dialog:

    // used imports
    import android.provider.Settings.ACTION_WIFI_ADD_NETWORKS
    import android.provider.Settings.EXTRA_WIFI_NETWORK_LIST
    import android.app.Activity
    import android.content.Intent
    import android.net.wifi.WifiNetworkSuggestion
    
    
    
    
    
    // show system dialog for adding new network configuration
        val wifiSuggestionBuilder = WifiNetworkSuggestion.Builder()
                    .setSsid("network SSID")
                    .build()
    
        val suggestionsList = arraylistOf(wifiSuggestionBuilder)
        val intent = new Intent(ACTION_WIFI_ADD_NETWORKS)
        intent.putParcelableArrayListExtra(EXTRA_WIFI_NETWORK_LIST, suggestionsList);
        activity.startActivityForResult(intent, 1000)
    

    The dialog looks like this:

    And then we just need to handle a result in onActivityResult method like this:

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == 1000) {
            if (resultCode == Activity.RESULT_OK) {
                // network succesfully added - User pressed Save
            } else if (resultCode == Activity.RESULT_CANCELED) {
                // failed attempt of adding network to system - User pressed Cancel
            }
        }
    }
    

    But as I've tested this code on Android devices that have older Android versions(lower then API30) installed I've got a crash every time I want it to show that dialog for adding a new network configuration. This is the crash:

    java.lang.RuntimeException: Unable to start activity: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.settings.WIFI_ADD_NETWORKS (has extras) }
    

    Looks like the new way is not back-supported out of the box. So, for API30 we can use a new Intent action, for API 28 and below we can still use the old way of adding Networks, but for API29 we have some kind of gray area where I was not able to find a good solution yet. If anyone has an idea what else to do please share it with me. ;)

提交回复
热议问题