Yugandhar Babu
Yugandhar Babu

Reputation: 10349

Turn on/off mobile network connection programmatically in android jelly bean

I am using below code to turn on/off mobile network.

        final ConnectivityManager conman = (ConnectivityManager) getApplicationContext().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, ON);

I tested this code with Android 2.3.X, 4.0.X and 4.1.X. It is working with only 2.3.X and 4.0.X but failed with 4.1.X.

I am getting java.lang.NoSuchFieldException: mService exception while testing with Android Jelly Bean.

Is there any other solution to my problem? I added all required permissions in manifest file.

Upvotes: 0

Views: 2357

Answers (1)

thampi joseph
thampi joseph

Reputation: 690

   try
              {
    dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
              } 
              catch (SecurityException e1) 
              {

                e1.printStackTrace();
              } 
              catch (NoSuchMethodException e1) 
              {

                e1.printStackTrace();
              }

                dataMtd.setAccessible(true); 
               try {

                dataMtd.invoke(conm,true);



              } 
}

Where datamtd is a method.. Try with this my friend. I found it successful in my previous app. Hope this may help you. Sorry if not, since I'm not much experienced.:)

Upvotes: 2

Related Questions