Reputation: 548
I want to do the following with my Android app:
192.168.0.1
which is emitting the Wi-fiI want to open a socket to communicate with this device
socket = new Socket();
socket.setSoTimeout(10000);
socket.connect(new InetSocketAddress("192.168.0.1", 80), 5000);
This code works on most of my test devices, except on Nexus 6 (Android 7) I have the following cases
Case where it's not workking
-> Socket can't open!
Case where it's working
--> Socket opens successfully!
What can I do programmatically to make it work in all cases?
Upvotes: 0
Views: 450
Reputation: 548
I finally found the solution
final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder req = new NetworkRequest.Builder();
req.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
cm.requestNetwork(req.build(), new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
cm.unregisterNetworkCallback(this);
network.bindSocket(socket);
socket.setSoTimeout(SOCKET_TIMEOUT);
socket.connect(new InetSocketAddress(ip, port), CONNECTION_TIMEOUT);
}
}
});
Upvotes: 1