2

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);
}
Taslim Oseni
  • 6,086
  • 10
  • 44
  • 69
Arun kumar
  • 1,894
  • 3
  • 22
  • 28
  • 3
    Please see this link : http://stackoverflow.com/questions/26539445/the-setmobiledataenabled-method-is-no-longer-callable-as-of-android-l-and-later – KishuDroid Sep 28 '15 at 07:24
  • hi if you want to disable the cellular data you can use just like this, TelephonyManager tm = (TelephonyManager)Android.App.Application.Context.GetSystemService(Context.TelephonyService); var tdata = tm.DataEnabled; if (tdata) tdata = false; – Adit Kothari Mar 27 '19 at 08:04

2 Answers2

12

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.

Ashish Shukla
  • 1,027
  • 16
  • 36
6

You cannot programatically enable internet connectio, but you can check if internet connection is present or not, if it is not persent, then you can tell the user to enable the internet connection.

Below code does that.

protected void createNetErrorDialog() {

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("You need internet connection for this app. Please turn on mobile network or Wi-Fi in Settings.")
        .setTitle("Unable to connect")
        .setCancelable(false)
        .setPositiveButton("Settings",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                Intent i = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
                startActivity(i);
            }
        }
    )
    .setNegativeButton("Cancel",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                MyActivity.this.finish();
            }
        }
    );
    AlertDialog alert = builder.create();
    alert.show();
}
penta
  • 2,536
  • 4
  • 25
  • 50