I run the following connectAndroidQ code to connect to open ap, and disconnectAndroidQ code to disconnect, but after connecting and disconnecting, the return value of NetworkInterface.getNetworkInterfaces() is null.
Before executing the code below, the return value of NetworkInterface.getNetworkInterfaces() is normal, but just running the code returns a null value.
test phone : pixel2 android version : 10
@RequiresApi(api = Build.VERSION_CODES.Q)
private boolean connectAndroidQ(@Nullable ConnectivityManager connectivityManager, ScanResult scanResult) {
if (connectivityManager == null) {
return false;
}
WifiNetworkSpecifier.Builder wifiNetworkSpecifierBuilder = new WifiNetworkSpecifier.Builder()
.setSsid(scanResult.SSID);
NetworkRequest networkRequest = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.setNetworkSpecifier(wifiNetworkSpecifierBuilder.build())
.build();
if (networkCallback != null) {
connectivityManager.unregisterNetworkCallback(networkCallback);
}
networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(@NonNull Network network) {
super.onAvailable(network);
connectivityManager.bindProcessToNetwork(network);
}
@Override
public void onUnavailable() {
super.onUnavailable();
}
};
connectivityManager.requestNetwork(networkRequest, networkCallback);
return true;
}
@RequiresApi(api = Build.VERSION_CODES.Q)
private boolean disconnectAndroidQ(@NonNull final ConnectivityManager connectivityManager) {
if (networkCallback != null) {
connectivityManager.unregisterNetworkCallback(networkCallback);
networkCallback = null;
}
return true;
}
Please help.
Thanks in advance.
I solved that problem by calling bindProcessToNetwork(null).
See the link below, Note that if network ever disconnects, all Sockets created in this way will cease to work and all host name resolutions will fail. This is by design so an application doesn't accidentally use Sockets it thinks are still bound to a particular Network. To clear binding pass null for network.