1

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);
   }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Sandip Patel
  • 1,003
  • 1
  • 8
  • 15
  • what is the exception? – AIK Sep 11 '18 at 11:48
  • Possible duplicate of [How can I enable or disable the GPS programmatically on Android?](https://stackoverflow.com/questions/4721449/how-can-i-enable-or-disable-the-gps-programmatically-on-android) – Cătălin Florescu Sep 11 '18 at 11:54
  • Possible duplicate of [How to enable mobile data on/off programmatically](https://stackoverflow.com/questions/32817552/how-to-enable-mobile-data-on-off-programmatically) – AIK Sep 11 '18 at 11:55
  • Those all are lower then for version 5.0. – Sandip Patel Sep 11 '18 at 11:57

1 Answers1

1

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);
Maxouille
  • 2,729
  • 2
  • 19
  • 42