Is a way to force OkHttp to do requests over the cellular network?
My app has certain requests that must be sent over the cellular network (3G, LTE, 4G, not Wifi). I'm using Retrofit and OkHttp for all the other network requests, so I would like to use it for these requests also. It looks like ConnectivityManger.registerDefaultNetworkCallback() could help but that only supports API 21+. I would like a solution for API 19+.
Assuming API 21+,
Network network; // filled in from ConnectivityManager.NetworkCallback
OkHttpClient client = new OkHttpClient.Builder()
.socketFactory(network.getSocketFactory())
.build();
you'll have to rebuild the OkHttpClient when the network goes away and comes back, but it's doable. You may be able to use a non-default network explicitly this way (some devices can keep the data connection up even when connected to and defaulting to WiFi).
On API 19 you may check ConnectivityManager.getActiveNetworkInfo() and refuse to operate if the type is WiFi, and check again from a BroadcastReceiver registered for android.net.conn.CONNECTIVITY_CHANGE.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With