Created
June 1, 2017 15:23
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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