11

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?

Ron
  • 24,175
  • 8
  • 56
  • 97
katit
  • 17,375
  • 35
  • 128
  • 256

2 Answers2

8

Switch to mobile network:

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 ConnectivityManagerclass.

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 a proxy:

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?

Detect a 'network change':

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

Update:

If you cannot show a dialog, at least send a status bar Notification so that user knows about the network switch sometime later.

Community
  • 1
  • 1
Ron
  • 24,175
  • 8
  • 56
  • 97
  • My app does data transfer in `AsyncTask` started by server. I can't show user anything because device screen might be off during that time. – katit Jun 23 '12 at 00:12
  • Also, I'm not sure how to _detect_ if thats proxy. I only see it in error logs submitted from device when I get HTML instead of JSON that I expect – katit Jun 23 '12 at 00:13
  • I have modified my answer.. send a Notification if you cannot show a dialog. – Ron Jun 23 '12 at 03:48
1

In your activities, Whenever you try to make call to your Web Services

Just Disable the WIFI if it's enabled. There will be many code snippets available on Internet for that like this

Now also Check that if Mobile data network is available or not, and If available make your call, otherwise show user a dialog that this app will require mobile data networks to do the tasks.

and as soon as you complete your HTTP Calls turn the WIFI ON again.

Community
  • 1
  • 1
MKJParekh
  • 34,073
  • 11
  • 87
  • 98