如何在 Android 中强制通过 Wi-Fi 而不是蜂窝网络进行 HTTP 连接?
我的应用程序必须检测连接到 Wi-Fi 网络的设备是否是所需的设备,然后以编程方式通过该 Wi-Fi 网络发出 HTTP 请求。我已经搜索过,但没有找到任何可以帮助我做到这一点的方法或类。
我想过禁用蜂窝网络,以便 HTTP 请求将通过 Wi-Fi 网络,但即使这样我也没有成功。 另外,我可以通过编程方式启用和禁用蜂窝网络和 Wi-Fi 网络吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没有办法强迫它使用其中之一。无论是 3G 还是 Wi-Fi,都会使用任何可用的网络(如果 Wi-Fi 连接,则 3G 关闭)。如果您不想根据当前使用的网络执行某些操作,您可以检查 Wi-Fi 是否未连接,如果是这种情况,则不执行任何操作,并提示用户。如果启用了纬度,Google 地图会执行类似的操作。
WifiManager 类有很多可能有用的方法你。
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.
您可以使用 Android 中 ConnectivityManager 类的
setNetworkPrefrence(ConnectivityManager.TYPE_WIFI)
you can go with
setNetworkPrefrence(ConnectivityManager.TYPE_WIFI)
of the ConnectivityManager class in Android您可以使用 OkHttp 和自定义 SocketFactory。有关更多信息,请参阅 https://github.com/square/okhttp/issues/2404细节。
You can use OkHttp and a custom SocketFactory. See https://github.com/square/okhttp/issues/2404 for more details.