In my app I am connecting to a device that has it's own WiFi network. In android 6 and above the system asks me after a few seconds if I want to connect to this network even though there is no internet connection. Only after approving that message I can connect to my device. I tried connecting to the network programmatically and not force the user to go to his settings and connect manually every time. I used the following code to connect to the devices network:
private void connectToWiFi(WifiManager wifiManager, String wifiName) {
WifiConfiguration configuration = new WifiConfiguration();
configuration.SSID = "\"" + wifiName + "\"";
configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wifiManager.addNetwork(configuration);
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for (WifiConfiguration i : list) {
if (i.SSID != null && i.SSID.equals("\"" + wifiName + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
break;
}
}
}
and also trying to force the app to use the WiFi connection and not the cellular data I am using :
NetworkRequest.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new NetworkRequest.Builder();
builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
connectivityManager.requestNetwork(builder.build(), new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
String ssid = wifiManager.getConnectionInfo().getSSID();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
connectivityManager.bindProcessToNetwork(null);
if (ssid.equals("\"" + Prefs.getWifiName(PUFMainActivity.this) + "\"")) {
connectivityManager.bindProcessToNetwork(network);
connectivityManager.unregisterNetworkCallback(this);
}
}
}
});
}
Although as long as the Cellular data is active the device doesn't apear to be connected. If I disable the Cellular data then it works fine. I need to know if there is a way to do what I want programmatically without telling the user to disable his Cellular data.
Thanks