Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Force OkHttp Request Over Mobile Network

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+.

like image 949
David Albers Avatar asked Oct 30 '25 15:10

David Albers


1 Answers

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.

like image 50
ephemient Avatar answered Nov 02 '25 04:11

ephemient