Issue
I have a crazy user case where there is a requirement to call some REST services only through mobile data (SIM). We'd like to send rest of the data through wifi.
Is it possible on Android to enforce through which kind of network to send data?
Is it possible in the same app and in the same session to send some data over mobile data and other through wifi?
Also, what would be the best way to test if the calls are sent over the right network type?
Solution
My use:
@TargetApi(21)
private fun getMobileNetWork() {
connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val builder = NetworkRequest.Builder()
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)//TRANSPORT_WIFI
val build = builder.build()
connectivityManager!!.requestNetwork(build, networkCallback)
}
val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
//Use the network to do your thing
}
override fun onLost(network: Network?) {
super.onLost(network)
}
override fun onUnavailable() {
super.onUnavailable()
}
}
Network usage in okhttp3:
val builder = OkHttpClient.Builder()
.connectTimeout(15L, TimeUnit.SECONDS)
.readTimeout(20L, TimeUnit.SECONDS)
.writeTimeout(15L, TimeUnit.SECONDS)
.socketFactory(network.socketFactory)
.dns {
network.getAllByName(it).asList()
}
Answered By - JKXY
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.