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 + "\"";
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wifiManager.addNetwork(conf);
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();
wifiManager.disconnect();
sicilia_ssid = networkSSID;
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
break;
}
}
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!
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:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
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;
break;
}
}
if (current_network != null)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
cm.bindProcessToNetwork(current_network);
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ConnectivityManager.setProcessDefaultNetwork(current_network);
}
}
}