How to force the HTTP connection over Wi-Fi instead of cellular in Android?

和自甴很熟 提交于 2019-12-18 06:59:07

问题


My application has to detect that the device connected to the Wi-Fi network is the required one and then fire a HTTP request over that Wi-Fi network programmatically. I have searched, but I didn't find any method or class which will help me to do this.

I thought of disabling the cellular network so that the HTTP request will go through the Wi-Fi network but even in this I didn't have success. And also, can I enable and disable the cellular and Wi-Fi networks programatically?


回答1:


There is no way to force it to use one or the other. Whatever network is available is used whether 3G or Wi-Fi (if Wi-Fi is connected 3G is off). If you don't want to do something based on which network is currently in use you can do a check whether Wi-Fi is not connected and don't do some action if that is the case, and prompt the user. Google Maps does something similar to this if Latitude is enabled.

The WifiManager class has a bunch of methods that may be useful to you.




回答2:


you can go with setNetworkPrefrence(ConnectivityManager.TYPE_WIFI) of the ConnectivityManager class in Android




回答3:


You can use OkHttp and a custom SocketFactory. See https://github.com/square/okhttp/issues/2404 for more details.



来源:https://stackoverflow.com/questions/5171770/how-to-force-the-http-connection-over-wi-fi-instead-of-cellular-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!