Skip to content Skip to sidebar Skip to footer

Android Turn On/off Mobile Data Using Code

I am trying to approach a problem in which I have to disable and then enable mobile data with some delay in between (reset mobile data 2G). step 1: disable mobile data step 2: wait

Solution 1:

Just put

Thread.sleep(1000);

in between the code statements (before setMobileData APIs) to achieve delay. The delay parameter is in milliseconds. So change it according to your requirement.

EDIT: Try putting the delay into a handler, using this code:

newHandler().postDelayed(newRunnable() {
@Overridepublicvoidrun() {
   //Whatever you want to do
    }
}, 1000);

Solution 2:

Try this may work. Use your code for turning off/on your packet data.

You should use a broadcast receiver for getting the events of connectivity.

IntentFilterintentFilter=newIntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
registerReceiver(broadcastReceiver, intentFilter);

Check the below link for details

Get notified on connectivity change

Solution 3:

Try (this will turn the data off then wait till it's off then on again):

setMobileDataEnabled(getApplicationContext(),false);
while(mobileDataEnabled(getApplicationContext()){
    //Just wait, don't do anything
}
//Turn it on heresetMobileDataEnabled(getApplicationContext(),true);

Lemme know if i couldn't get you properly!

Solution 4:

// first check whether it is on\off...

publicvoidsetMobileDataEnabled(Context context, boolean status)throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException 
 {
    finalConnectivityManagerconman= (ConnectivityManager)  context.getSystemService(Context.CONNECTIVITY_SERVICE);
    finalClassconmanClass= Class.forName(conman.getClass().getName());
    finalFieldconnectivityManagerField= conmanClass.getDeclaredField("mService");
    connectivityManagerField.setAccessible(true);
    finalObjectconnectivityManager= connectivityManagerField.get(conman);
    finalClassconnectivityManagerClass=  Class.forName(connectivityManager.getClass().getName());
    finalMethodsetMobileDataEnabledMethod= connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
    setMobileDataEnabledMethod.setAccessible(true);

    setMobileDataEnabledMethod.invoke(connectivityManager, status);
}

Post a Comment for "Android Turn On/off Mobile Data Using Code"