I'm looking for your help / ideas related to the problem below:
What I want to achieve:
- route requests through mobile network on Android, using Retrofit2, OktHttp
What I did:
- obtained the needed Network instance using ConnectivityManager
- set the socketFactory for OkHttpClient to use the one from the Network instance
- specified these permissions in AndroidManifest.xml.:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
Example code:
val network: Network = connectivityManager.allNetworks.first {
connectivityManager.getNetworkCapabilities(it)?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) == true
}
val okHttpClient = OkHttpClient.Builder()
.socketFactory(network.socketFactory)
.build()
Result:
- exception is thrown: java.net.SocketException: Binding socket to network 505 failed: EACCES (Permission denied)
Notes / Disclaimer:
- the above works for WiFi
- I know this is a bad practice: it is not the default behaviour of the application. Users can opt-in and opt-out anytime. There's a specific use case in which this makes sense.
If you have any ideas on what I'm doing wrong, or why isn't it working for mobile networks, please let me know.