1

How do I programmatically turn off 4G / data in Android 8.0?

Not Wifi, but 4G/Data.

Running the following source will turn the device off.

public void onClick(View view){
        ConnectivityManager dataManager;
        dataManager  = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        Method dataMtd = null;
        try {
            dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        dataMtd.setAccessible(true);
        try {
            dataMtd.invoke(dataManager, true);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

4 Answers4

1

Following code works for me on Kotlin:

fun disable4GNetwork(context: Context) {
val connectivityManager =
    context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val request: NetworkRequest.Builder?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    request = NetworkRequest.Builder()

    request.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
    connectivityManager.requestNetwork(
        request.build(),
        object : ConnectivityManager.NetworkCallback() {

            override fun onAvailable(network: Network) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    ConnectivityManager.setProcessDefaultNetwork(network)
                }
            }
        }
    )
}

}

Sam
  • 446
  • 7
  • 17
0

Actually, since Android 5.0 Lollipop you cannot enable nor disable 4G/Phone Data anymore. Anyway for previous versions and only on rooted devices this solution worked.

To disable WiFi this code should work:

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

Where "status", at the second loc, should be true/false.

shannontesla
  • 885
  • 1
  • 8
  • 27
0

You need to root the device,use TelephonyManager instead of ConnectivityManager and add the permission of MODIFY_PHONE_STATE.

Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
Pravin Yadav
  • 337
  • 3
  • 12
0

Ok with Sam Solution but not forgot to add permission in your manifest

    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
thelastworm
  • 544
  • 4
  • 14