WifiConfiguration enable network in Lollipop

I was working on Wifi project, there is a module that enable user to join wifi programatically.

In kitkat and below it’s working successfully, but in Lollipop it’s not working.

  • WebSocket in Android WebView
  • Navigation Drawer onNavigationDrawerItemSelected called before MainActivity onCreate?
  • Android develop LCD font
  • 'RealmNoticeModelClass' has a primary key, use 'createObject(Class<E>, Object)' instead
  • Android: java.lang.SecurityException: Permission Denial: start Intent
  • While Uploading App in Google Play is shows Upload failed You need to check the icon inside your APK because it is not valid
  • Here is the code :

    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    WifiConfiguration wifiConfiguration = new WifiConfiguration();
    wifiConfiguration.SSID = "\"testSSID\"";
    wifiConfiguration.hiddenSSID = true;
    wifiConfiguration.status = WifiConfiguration.Status.ENABLED;
    wifiConfiguration.allowedKeyManagement
    .set(WifiConfiguration.KeyMgmt.NONE);
    netId = wifiManager.addNetwork(wifiConfiguration);
    Log.d("WifiPreference", "add Network returned " + netId);
    boolean checkEnableWifi = wifiManager.enableNetwork(netId, true);
    Log.d("WifiPreference", "enableNetwork returned " + checkEnableWifi);
    

    my tested device is nexus 5 build number LRX21O, is ther something wrong in my code or bug on Lollipop?

    Related posts:

    Set Default Tab for Fragment/ViewPager setup
    Change options menu during runtime - invalidateOptionsMenu()
    How to create a slider screen (As in Tweetdeck) in Android?
    Android: How to use AlarmManager
    How to implement RecyclerView with CardView rows in a Fragment with TabLayout
    Can&#039;t activate Preview mode Android Studio
  • Can't upload Android app to device (stale dexed jars)
  • Need help dealing with a Fatal Exception caused by java.lang.IncompatibleClassChangeError
  • How to make a LinearLayout scrollable
  • How to change background color of action bar without increasing min sdk?
  • Android Live Wallpaper practices for performance and battery saving?
  • Accessing SharedPreferences through static methods
  • 5 Solutions collect form web for “WifiConfiguration enable network in Lollipop”

    Faced similar issue on lollipop.

    Disabling other networks manually, an then reconnecting wifi manager solved the issue.

    boolean enableNework(String ssid, Context cxt) {
        boolean state = false;
        WifiManager wm = (WifiManager) cxt.getSystemService(Context.WIFI_SERVICE);
        if (wm.setWifiEnabled(true)) {
            List<WifiConfiguration> networks = wm.getConfiguredNetworks();
            Iterator<WifiConfiguration> iterator = networks.iterator();
            while (iterator.hasNext()) {
                WifiConfiguration wifiConfig = iterator.next();
                if (wifiConfig.SSID.equals(ssid))
                    state = wm.enableNetwork(wifiConfig.networkId, true);
                else
                    wm.disableNetwork(wifiConfig.networkId);
            }
            wm.reconnect();
        }
        return state;
    }
    

    Try this. Do not disable other saved networks. As it will hinder the fallback of wifi on other networks when your selected network is not available. Play with the priority.

    /*
     *  Max priority of network to be associated.
     */
    private static final int MAX_PRIORITY = 999999;
    
    /**
     * Allow a previously configured network to be associated with.
     */
    public boolean enableNetwork(String ssid) {
        boolean state = false;
        List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
    
        if(list != null && list.size() > 0) {
            for( WifiConfiguration i : list ) {
                if(i.SSID != null && i.SSID.equals(convertToQuotedString(ssid))) {
    
                    wifiManager.disconnect();
    
                    int newPri = getMaxPriority() + 1;
                    if(newPri >= MAX_PRIORITY) {
                        // We have reached a rare situation.
                        newPri = shiftPriorityAndSave();
                    }
    
                    i.priority = newPri;
                    wifiManager.updateNetwork(i);
                    wifiManager.saveConfiguration();
    
                    state = wifiManager.enableNetwork(i.networkId, true);
                    wifiManager.reconnect();
                    break;
                }
            }
        }
    
        return state;
    }
    
    private int getMaxPriority() {
        final List<WifiConfiguration> configurations = wifiManager.getConfiguredNetworks();
        int pri = 0;
        for (final WifiConfiguration config : configurations) {
            if (config.priority > pri) {
                pri = config.priority;
            }
        }
        return pri;
    }
    
    private void sortByPriority(final List<WifiConfiguration> configurations) {
        Collections.sort(configurations,
            new Comparator<WifiConfiguration>() {
                @Override
                public int compare(WifiConfiguration object1, WifiConfiguration object2) {
                    return object1.priority - object2.priority;
                }
            });
    }
    
    private int shiftPriorityAndSave() {
        final List<WifiConfiguration> configurations = wifiManager.getConfiguredNetworks();
        sortByPriority(configurations);
        final int size = configurations.size();
        for (int i = 0; i < size; i++) {
            final WifiConfiguration config = configurations.get(i);
            config.priority = i;
            wifiManager.updateNetwork(config);
        }
        wifiManager.saveConfiguration();
        return size;
    }
    
    /**
     * Add quotes to string if not already present.
     *
     * @param string
     * @return
     */
    public static String convertToQuotedString(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
    
        final int lastPos = string.length() - 1;
        if (lastPos > 0
                && (string.charAt(0) == '"' && string.charAt(lastPos) == '"')) {
            return string;
        }
    
        return "\"" + string + "\"";
    }
    

    Try adding wifiManager.setWifiEnabled(true); at the end of your code.

    try setting false where you are trying to diable other networks.

    wifiManager.enableNetwork(netId, false);
    

    and one more thing if your addNetwork succeeds then you can proceed with the rest. if it returns a -1 you cannot call enableNetwork as the netId you are using would be -1. so what you could ideally do is

    netId = wifiManager.addNetwork(wifiConfiguration);
    if(netId >= 0){
    Log.d("WifiPreference", "add Network returned " + netId);
    boolean checkEnableWifi = wifiManager.enableNetwork(netId, true);
    Log.d("WifiPreference", "enableNetwork returned " + checkEnableWifi);
    }
    

    I was facing a situation on Nexus 7 connecting to hp printer in which the method enablenetwork(id,true) return true but still does not connect. Answer from @Santosh and @Seraphim helped me..Disabling each network and enabling only the required SSID worked.

    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.