Tuesday, 23 August 2016

Programatically connecting to a WiFi network with Captive Portal on Marshmallow

Android platform is continuously growing and coming up with new concepts and features that are optimized to save battery or provide a better user experience. Each new Android update comes up with new APIs along with changes in older ones. At times these changes might need developers to handle additional scenarios to provide features that are supported in newer versions.

One such change was seen with an upgrade of Android OS to Lollipop and Marshmallow. With these upgrades, the system changed how it handles the connection to Networks. Starting from Lollipop, if a device is connected to both 3G and WiFi where WiFi network doesn't have internet connectivity, the device uses the 3G network to send data. This was done so that devices don't automatically start using WiFi network that has restrictions or has a captive portal to connect to the internet.

With start in active development in the IoT field, there might be use cases where a device might want to connect to a local WiFi network that doesn't provide internet. There might be other use cases where your app might want to connect to a WiFi network that is behind a captive portal and for automatically logging in to the network you might need to route your internet traffic through WiFi to make API calls needed to authenticate.

For such scenarios, Android does provide mechanisms for your app to explicitly use a particular network with specific capabilities to route all or parts of its network traffic.



Steps to follow (Assuming that WiFi on the device is enabled):
  1. Scan for new networks should be initiated to get the latest available networks. But in this case, we would assume that a particular network is already available, found during scan initiated by the system automatically. Create a network request and register for callback in which app should bind to the network when available. This would ensure that all the network traffic for the current app is routed through this network.
Now the callback would be received when the device is connected to the required network.
  1. Create an open WifiConfiguration with required SSID to which your app needs to connect. 
A restriction that was put starting from Marshmallow was that the app can only modify those WiFi networks that it has created. The system doesn't allow modification of networks that other apps or users have created. So, adding the network might fail if the network already exists in the list (the system might auto connect to the network once it's detected). Additional steps are needed to handle such a scenario:
  1. Check networkId returned by addNetwork(), in case it is -1 (unable to add a network with configuration), try finding the network with the same SSID among the list of existing networks. 
  2. In case any network with the same SSID already exists, get networkId of that network.

So, lets implement this:


Calling connectToSSID() will connect the device to the network with given SSID. This will, in turn, provide a callback to onAvailable() of NetworkCallback in which the app would bind to this network. After binding is done, listener.onNetworkBound() is called in which a login request could be initiated.



This will make the OS to check if there is internet connectivity available in the network to which app is bound. If there is, OS would switch to make it an active network. Lastly, the app should unbind from the network.

If you are looking to solve similar problems or need to connect to WiFi networks in your project for similar reasons, there is an open source Android library that provides all these functionalities and is easy to use. I would recommend you to give it a shot: android-wificonnect


  1. Thanks for the tut, I had to modify it a little for my specific needs but it connects to a wifi enabled device now.

  2. Hey!
    I am working on an app that will you this functionality.
    However, In the above explanation i could not understand what will be the components of NetworkStateChangeListner?

    1. It's just a custom listener that can be notified when onAvailable NetworkCallback is received. You can have a look at complete code here: https://github.com/nishkarsh/android-wificonnect

  3. Hi Nishkarsh,

    I have been trying to connect to my wifi router programatically for some time now. I have more details at http://stackoverflow.com/questions/41712432/connecting-to-wifi-network-automatically-in-android-5-and-6 Are you familiar with the issue? Do you have any pointers?


    1. Hey Arjun,

      Can you please let me know if mobile data is turned on at the time the app is trying to connect to WiFi? I have not yet got the time to try it out. Can you try it out with different states of WiFi (when it's already disabled or connected to some other SSID) and without having a sim card (or mobile data turned off). This might not even be related but might help in finding out the exact problem. I will myself try it out and let you know in case I find something. :)

      Sorry for the delayed reply!


    2. I have the following observations.

      1. The issue so far is specific to 1 android 6 Samsung tablet and 1 android 5 Micromax phone. It works just fine on 3 other android 6 phones, 1 android N phone and Android 4.4.2 phone.
      2. The access point ends up in wifi_ap_disabled state in the problematic cases consistently. Both addNetwork and enableNetwork calls are affirmative.
      3. These access points are not that of a router wifi but that of other phones that broadcast. The problematic phones can programatically connect to wifi hotspots (setup manually and not in the programatic way as I would like to) without any issue.
      4. SIM enabled/disabled state or wifi state with a different connected network doesn't change the dynamics for both working and problematic phones.

      This makes me think that it is a combination of phones/tabs (and not OS) and the access point broadcast configuration. Do you think I should be playing around with some config parameters?


    3. Same here. Android N works fine here, too. It's a Samsung Galaxy Tab A T585 which makes trouble. On a rooted device it can be fixed with "su" and "settings put global captive_portal_detection_enabled 0", now delete your stored wifi configurations (aka networks) and add them again (do this in the android settings).

  4. Hi,
    I've implement this code but i can't connect besides the code returns me an idnetwork.

    Can you please help me?

    1. Hey Bernardo!
      Are you getting a non-negative networkId? If that's the case, can you try listening to NETWORK_STATE_CHANGED_ACTION broadcast and tell your observations.

  5. Hello Nishkarsh,

    I have same requirement in my app which you have explained. I used your code to and it is working fine on all os.

    But I am, facing one issue. Case is like below.
    1. Wifi is enabled.
    2. Location is disabled.
    3. Wifi is latched to my captive portal(Android OS latched it to wifi).
    4. I am checking whether wifi is latched to my wifi network using below code

    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    if (wifiInfo != null && WifiUtils.IsMyWifi(wifiInfo.getSSID(), context) && wifiInfo.getIpAddress() != 0 && wifiInfo.getNetworkId() != -1)
    return true;
    return false;

    5. If it latched to my network then I am hitting capetive portal but it is giving me 200 always. As per my observation app network is not bind to wifi.

    How I can bind the app network to wifi, when wifi is already latched by os.

    Can you please help me to resolve this issue?

    1. Hey Abhijeet!

      Could you please tell which OS version are you trying this on? Also if I understand it correctly, you are facing problems binding to a WiFi network which is behind captive portal and when you already have mobile data turned on. Am I right on this? In that case, could you please tell if it all works when mobile data is turned off or when location is enabled?

  6. HI Nishkarsh..Thanks you for this porst.Is your program only for open networks?? i read about this in your github README. Do you have any idea how we can authenticate for WPA/WEP.

    1. Hey Rishi,

      Sorry for delayed reply! As of now, the library supports only initiating connection to open networks, however, it shouldn't take much efforts to modify it to connect to networks that require authentication. I have planned it to have this support for future release but haven't been getting much time lately.

      If you haven't done it already, lemme know and I can help you through the steps to do it.

  7. When you initially set up the hotspot feature on your iPhone, you are reminded that you can also use bluetooth to share the connection.http://www.chrismartslaw.com/


  9. Hello Nishkarsh,
    Whenever wifi-enabled slider button is enabled(ON), wpa_supplicant service gets started and scan's the SSID of the routers(I can print those SSIDS listed in logcat messages). But on Display "Searching for Wifi Networks" is continuously displayed. What could be the reason?. How to resolve the issue?. How to get the listing of Wifi networks on the Display? Please let me know. Working on Android Marshmallow.


    1. Hey Firdosh,

      Is this implemented in your own app or are you trying this out from global WiFi settings? I am sorry but I could not get the specific functionality you want to achieve. If you are trying this out in your own android app, are you doing this using the approach mentioned above? You could try this sample out too: https://github.com/nishkarsh/AndroidWifiConnectSample/tree/master/app/src/main/java/com/intentfilter/androidwificonnectsample

      Let me know if this helps. Let me also know if you meant something else.

  10. Hello Nishkarsh,
    I am not implementing any apps. My task is get wifi up and running on Android M. (From Driver level to GUI level).
    As of now I was able to bring up wifi drivers(TI's) on customized ARM Board Successfully. So whenever I try to enable wifi on from the settings->wifi "Searching for Wifi Networks" is getting displayed. But none of the router's info is getting listed on the Display screen. Even Add Network button is disabled. Would you please let me know any configuration or settings i am missing. I do have access to Full Android Source code. I can build and Flash on to the board. Please let me know if you require further information.