Teiki Teiki - 1 year ago 80
Java Question

Difference between using java to connect to an adhoc wifi or do it manually

Strange problem that I have here.

I'm making an app that connect to a wireless adhoc network from a camera.
(So there is no Internet connection in wifi).

Here is the java code I use, to be able to automatically connect the Android phone to the camera wifi:

WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\"";

LocalBroadcastManager.getInstance(context).registerReceiver(mWifiScanReceiver, new IntentFilter(TAG_WIFI_CONNECTED));

List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.contains(networkSSID)) {
if (old_networkId != i.networkId && wifiManager.getConnectionInfo() != null)
old_networkId = wifiManager.getConnectionInfo().getNetworkId();
sicilia_ssid = networkSSID;

wifiManager.enableNetwork(i.networkId, true);

This code work: the device does connect to the wifi I want to but:

Here is the problem

I'm using a specific API to dialog with the camera.
If I use this code to connect to the wifi, the API will not work. But if I connect manually to the wifi (with settings app), there is no problem...
If I disable cellular data, I can use the code to automatically connect to the camera.
So it looks like that cellular data is prioritize over adhoc wifi but only when the connection was made in java code...

So what is the difference between both way?
Do I need to add some more code?
Thank you a lot!

Answer Source

I found the solution here :

"From Lollipop onwards the OS became a little more intelligent, allowing multiple network connections and not routing data to networks that don’t have Internet connectivity"

So I added this code once the connection was made:

        ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        Network current_network = null;
        for (Network n : cm.getAllNetworks())
            if (cm.getNetworkInfo(n).getTypeName().equals("WIFI")) {
                current_network = n;

        if (current_network != null)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download