Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force HttpURLConnection to use mobile network and fallback to WiFi

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?

like image 990
katit Avatar asked Jun 20 '12 00:06

katit


1 Answers

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.

like image 193
Ronnie Avatar answered Nov 15 '22 20:11

Ronnie