Alex
Alex

Reputation: 548

Opening a socket only works when 3G/4G is disabled?

I want to do the following with my Android app:

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

Answers (1)

Alex
Alex

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

Related Questions