I need to Turn ON/OFF Mobile data programmatically. Below code is not working for 5.x. Can you please help me. Thanks in advance.
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); }
03-30 12:42:29.466: W/System.err(5966): java.lang.NoSuchMethodException: setMobileDataEnabled [boolean] 03-30 12:42:29.466: W/System.err(5966): at java.lang.Class.getMethod(Class.java:664) 03-30 12:42:29.466: W/System.err(5966): at java.lang.Class.getDeclaredMethod(Class.java:626)
java.lang.NoSuchMethodException: setMobileDataEnabled [boolean] @ below line.
final Method setMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
In Android L 5.xx the hidden API setMobileDataEnabled method is removed and it can no longer be used. You can verify this in android lolipop source code under /frameworks/base/core/java/android/net/ConnectivityManager.java.
If you still insist to perform it, you can use code snippet answered by Kushal but getDataEnabled is a system api, which normal user applications cant access. There is also one more system api available setDataEnabled under TelephonyManager. (/frameworks/base/telephony/java/android/telephony/TelephonyManager.java)
It also needs the permission "android.permission.MODIFY_PHONE_STATE" which will work only on rooted devices.
When executing the code you get a SecurityException stating that Neither user 10089 nor current process has android.permission.MODIFY_PHONE_STATE.
A permission MODIFY_PHONE_STATE should be added I got this from Answer Thank you Muzikant