Temporarily disable Internet access in Android?

I want to set up a test to make sure my code works correctly when there is no Internet access. Is there a way to temporarily disable Internet access for testing?

I tried to look back, but could not find it.

Thanks in advance, Cool

+6
source share
3 answers

This code sample should work on Android phones that work with gingerbread and above: this is turning on / off the 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); } 

Remember to add this line to the manifest file

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

In addition, I know how to enable or disable Wi-Fi:

 WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE); wifiManager.setWifiEnabled(status); 

where the status can be true or false as required.

Also in the manifest:

 <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> 
+4
source

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 disconnect the Data connection, you can use this solution here: fooobar.com/questions/126270 / .... This method, however, does not work on 2.3 +

This answer here has a solution for both 2.3+ and 2.2 and below: fooobar.com/questions/155466 / .... You can perform a simple API check and decide which piece of code to execute. Something like this should make 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 will be later. I personally have never met to check the ability to enable or disable data, though.

Supports authors of related solutions .; -)

NOTE. Data Connectivity Solutions are based on an unofficial API and may not work in future versions.

+2
source

If you use an emulator, you can disable Internet access for it in the DDMS settings.

Departure:

0
source

All Articles