I want to set up a test to see if my code works properly when there is no internet access. Is there a way to temporarily shut down internet access for a test?
I tried looking around but I couldn't find it.
I want to set up a test to see if my code works properly when there is no internet access. Is there a way to temporarily shut down internet access for a test?
I tried looking around but I couldn't find it.
This code sample should work for android phones running gingerbread and higher: This enable/disable data connection
private void setMobileDataEnabled(Context context, boolean enabled) {
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final Class conmanClass = Class.forName(conman.getClass().getName());
final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(conman);
final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
}
Don't forget to add this line to your manifest file
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
Also, I know of enabling or disabling wifi:
WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(status);
where status may be true or false as per requirement.
Also at manifest:
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
Well, to disable Wifi, you can use this code:
WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true); // "true" TO ENABLE || "false" TO DISABLE
To disable the Data connection, you could use the solution here: https://stackoverflow.com/a/4304110/450534. This method, however, does not work on 2.3+
This answer here has a solution for both 2.3+ and 2.2 and below: https://stackoverflow.com/a/12535246/450534. You could do a simple API check and decide which piece of code to run. Something like this should get you set up:
int currentAPIVersion = android.os.Build.VERSION.SDK_INT;
if (currentAPIVersion >= android.os.Build.VERSION_CODES.GINGERBREAD) {
// RUN THE CODE FOR 2.3+
} else {
// RUN THE CODE FOR API LEVEL BELOW 2.3
}
See which of the two works for you. I suspect, it would be the later. I have personally never gotten around to testing the enabling or disabling Data connectivity though.
Props to the authors of the linked solutions. ;-)
NOTE: The Data Connectivity solutions are based on unofficial API's and may not work in future releases.
If you are using emulator, you can turn off internet access for it in DDMS
settings.
Check out: