Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable mobile data on/off programmatically [duplicate]

In android how to enable mobile data on and off in android 4.4 and above versions. I have used this code but it is not working in android 4.4 and above versions:

private void setMobileDataEnabled(Context context, boolean enabled){
    final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final Class conmanClass = Class.forName(conman.getClass().getName());
    final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
    iConnectivityManagerField.setAccessible(true);
    final Object iConnectivityManager = iConnectivityManagerField.get(conman);
    final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
    final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
    setMobileDataEnabledMethod.setAccessible(true);

    setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
}
like image 918
Arun kumar Avatar asked Sep 02 '26 04:09

Arun kumar


1 Answers

You cannot access mobile data on / off programmaticaly above android 4.4 .It have been made stopped for security reasons ,instead you can ask the user using a dialog to enable the mobile data and then if he enable you can do your task.

like image 172
Ashish Shukla Avatar answered Sep 03 '26 18:09

Ashish Shukla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!