Sandip Patel
Sandip Patel

Reputation: 1043

Enable/Disable Mobile Data Programmatically (Lollipop and Above) without Root

I am trying to toggle android data connection programatically in android lollipop and above but it doesn't work and got exception always.

This is my code

public void setMobileDataState(boolean mobileDataEnabled)
{
   try
   {
       TelephonyManager telephonyService = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

       Method setMobileDataEnabledMethod = telephonyService.getClass().getDeclaredMethod("setDataEnabled", boolean.class);

       if (null != setMobileDataEnabledMethod)
       {
           setMobileDataEnabledMethod.invoke(telephonyService, mobileDataEnabled);
       }
   }
   catch (Exception ex)
   {
        Log.e(TAG, "Error setting mobile data state", ex);
   }
}

Upvotes: 1

Views: 805

Answers (1)

Maxouille
Maxouille

Reputation: 2911

This method only works for root. Actually, since Lollipop update, it's not possible to enable/disable the mobile data programmatically. You can do it on lower version with this :

private void setMobileDataEnabled(Context context, boolean enabled) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
    final ConnectivityManager conman = (ConnectivityManager)  context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final Class conmanClass = Class.forName(conman.getClass().getName());
    final Field connectivityManagerField = conmanClass.getDeclaredField("mService");
    connectivityManagerField.setAccessible(true);
    final Object connectivityManager = connectivityManagerField.get(conman);
    final Class connectivityManagerClass =  Class.forName(connectivityManager.getClass().getName());
    final Method setMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
    setMobileDataEnabledMethod.setAccessible(true);

    setMobileDataEnabledMethod.invoke(connectivityManager, enabled);

Upvotes: 1

Related Questions