Jeyavel Natesan Jeyavel Natesan - 7 months ago 17
Android Question

How to use 3G Connection in Android Application instead of Wi-fi?

How to use 3G Connection in Android Application instead of Wi-fi?

I want to connect a 3G connection, is there any sample code to connect to 3G instead of Wi-fi?


The T-Mobile 'My Account" app does this, if you are connected to a WiFi connection it tells you that their program will not work over WiFi and then asks the user if they want to turn off the WiFi connection. If you choose "No" then the application exits, if you choose "Yes" then the app turns off your WiFi connection and then continues with starting up.

I think this is a good model to follow, it will ensure that your app is not being ran over WiFi and allows the user to decide if they want to turn off WiFi or not. An improvement on this model would be to turn wifi back on when the user navigates away from your app.

I haven't tested the following code, but it looks like it should work (modified from here)

use the following permissions in your manifest

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>

and here is some actual code to turn wifi on/off

private WifiManager wifiManager;

public void onCreate(Bundle icicle)

    wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);


If you do not want to go down that route it looks like you might be able to tell the phone that you would prefer to use the mobile data network rather than the wifi network.

The Android ConnectivityManager offers a function setNetworkPreference. This function is not really documented as you can tell if you click the link. I would paly around with it though because the constants that are defined seem to hint that you can set this to either TYPE_MOBILE or TYPE_WIFI and there is a DEFAULT_NETWORK_PREFERENCE constant as well that is defined as being 0x00000001 which is the same as TYPE_WIFI. So try getting access to a ConnectivityManager by calling


and then try using the setNetworkPreference() function.

It doesn't appear to require any permissions in the manifest but it might require the CHANGE_NETWORK_STATE permission or something along those lines.

If you do sue the setNetworkPreference function it would probably be best to also set the Network Preference back to its original values (received from getNetworkPreference)

I hope this helps.