In Android, you can enable or disable Wi-Fi or internet connectivity using the WifiManager
and ConnectivityManager
classes.
Here's an example of how to enable or disable Wi-Fi in Android using the WifiManager
class:
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); // Enable Wi-Fi wifiManager.setWifiEnabled(true); // Disable Wi-Fi wifiManager.setWifiEnabled(false);
To enable or disable internet connectivity in Android, you can use the ConnectivityManager
class and its setMobileDataEnabled()
method. Here's an example of how to enable or disable internet connectivity in Android using the ConnectivityManager
class:
ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); try { // Enable internet connectivity Method setMobileDataEnabledMethod = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class); setMobileDataEnabledMethod.setAccessible(true); setMobileDataEnabledMethod.invoke(connectivityManager, true); // Disable internet connectivity setMobileDataEnabledMethod.invoke(connectivityManager, false); } catch (Exception e) { // Handle errors }
Keep in mind that to use the above code, your app must have the android.permission.ACCESS_NETWORK_STATE
and android.permission.CHANGE_NETWORK_STATE
permissions. You can add these permissions to your app's manifest file.
<manifest> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> ... </manifest>