Skip to content

Instantly share code, notes, and snippets.

@onyxmueller
Created June 1, 2017 15:23
Show Gist options
  • Save onyxmueller/29903e23fccdf921b4c1f846126b1e6a to your computer and use it in GitHub Desktop.
Save onyxmueller/29903e23fccdf921b4c1f846126b1e6a to your computer and use it in GitHub Desktop.
An example Java class file demonstrating how to create a mobile/cellular-only OkHttp based network.
public class MobileOnlyNetworkTest {
private static final int TIMEOUT_SECONDS = 30;
public Test(Context context) {
Network network = getCellNetwork(context);
if (network != null) {
OkHttpClient client = getNetworkClient(network);
}
}
private Network getCellNetwork(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Network[] networks = cm.getAllNetworks();
for (Network network: networks) {
NetworkInfo ni = cm.getNetworkInfo(network);
if (ConnectivityManager.TYPE_MOBILE == ni.getType()) {
// Cell network!
return network;
}
}
return null;
}
private OkHttpClient getNetworkClient(Network bindNetwork) {
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.readTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.socketFactory(bindNetwork.getSocketFactory())
.retryOnConnectionFailure(true)
.followRedirects(true)
.followSslRedirects(true);
return builder.build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment