My application uses HttpURLConnection
to connect to my REST services. I log errors and noticed that what happens occasionally is that user get's WiFi connection but it has proxy.
For example, those airport wifi's that redirect you to pay pages and then let you use internet. My code does not follow redirects.
What I really want is to ignore presence of WiFi and force communication over 3G/4G/E whatever. How can I do that on Android?
As soon as you detect a proxy, pop up a dialog telling the user that your app cannot use that network and hence you are switching to the mobile network. You can switch to a mobile network using ConnectivityManager
class.
ConnectivityManager cm;
cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
cm.setNetworkPreference(ConnectivityManager.TYPE_MOBILE);
and switch back to the default when you are done:
cm.setNetworkPreference(ConnectivityManager.DEFAULT_NETWORK_PREFERENCE);
Detect proxy using the following snippet
HttpURLConnection conn;
...
if (conn.getResponseCode() == HTTP_PROXY_AUTH){
// You got a '407: Proxy authentication required' response.
// Set the networkPreference() here and retry when
// network connection changes to TYPE_MOBILE.
}
You can check this post to know how to use a HttpURLConnection through a proxy : How do I make HttpURLConnection use a proxy?
To know how to detect 'network change' see this post : Android, How to handle change in network (from GPRS to Wi-fi and vice-versa) while polling for data
If you cannot show a dialog, at least send a status bar Notification
so that user knows about the network switch sometime later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With