0

I used these code, which work fine in pre-Lollipop but didn't work on Lollipop. All i want to do that is just Enable/Disable Mobile Data.

 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);
    }

Help me out tell me how i do that in lollipop?

Ambitious Person
  • 295
  • 1
  • 3
  • 15
  • possible duplicate of [Enable/disable data connection in android programmatically](http://stackoverflow.com/questions/11555366/enable-disable-data-connection-in-android-programmatically) – Kushal May 28 '15 at 11:09
  • @Kushal my code is same, but it didn't work on Lollipop as they also mentioned that in comments below. – Ambitious Person May 28 '15 at 11:11

1 Answers1

1

For Wifi Enabling

    WifiManager wifiManager = (WifiManager) mContext
    .getSystemService(Context.WIFI_SERVICE);
    wifiManager.setWifiEnabled(true);

For Data Enabling:

   ConnectivityManager dataManager;
dataManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
Method dataMtd = null;
try {
    dataMtd = ConnectivityManager.class
            .getDeclaredMethod(
                    "setMobileDataEnabled",
                    boolean.class);
} catch (NoSuchMethodException e) {
    e.printStackTrace();
}
dataMtd.setAccessible(true);
try {
    dataMtd.invoke(dataManager, true);
} catch (IllegalAccessException
        | IllegalArgumentException
        | InvocationTargetException e) {
    e.printStackTrace();
}
learner
  • 3,092
  • 2
  • 21
  • 33