5

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 till mobile data gets disabled

step 3: some delay say 2 seconds

step 4: enable mobile data

step 5: wait till mobile data gets enabled

step 6: continue with the program.....

doing some research I came up with this...

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button start = (Button)findViewById(R.id.button1);
        start.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                    if(!mobileDataEnabled(getApplicationContext())){
                    setMobileDataEnabled(getApplicationContext(),true);
                    Toast.makeText(getApplicationContext(), "ENABLED", Toast.LENGTH_SHORT).show();
                    }else{
                    setMobileDataEnabled(getApplicationContext(),false);
                    Toast.makeText(getApplicationContext(), "DISABLED", Toast.LENGTH_SHORT).show();
                    }

            }
        });
    }

//the method below enables/disables mobile data depending on the Boolean 'enabled' parameter.
private void setMobileDataEnabled(Context context, boolean enabled) {
        final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        Class conmanClass = null;
        try {
            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);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
// below method returns true if mobile data is on and vice versa
 private boolean mobileDataEnabled(Context context){
        boolean mobileDataEnabled = false; // Assume disabled
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        try {
            Class cmClass = Class.forName(cm.getClass().getName());
            Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
            method.setAccessible(true); // Make the method callable
            // get the setting for "mobile data"
            mobileDataEnabled = (Boolean)method.invoke(cm);
        } catch (Exception e) {
            // Some problem accessible private API
            // TODO do whatever error handling you want here
        }
        return mobileDataEnabled;
    }

The above code will turn on/off mobile data but it happens really quick. this quick that the mobile data doesn't even turn off actually. how do I add a delay in between and achieve the steps I mentioned above? any help would be appreciated. thanks!

Tim B
  • 40,716
  • 16
  • 83
  • 128
user2933671
  • 273
  • 3
  • 5
  • 19
  • I would use an AsyncTask to run your code in another thread. This way, using a `sleep` method would not block the main thread. – cosmincalistru Apr 16 '14 at 05:13

5 Answers5

2

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:

new Handler().postDelayed(new Runnable() {
@Override
public void run() {
   //Whatever you want to do
    }
}, 1000);
SoulRayder
  • 5,072
  • 6
  • 47
  • 93
  • I have already tried that. but by doing that I am blocking the UI thread. which is not a good for applications and user experience. – user2933671 Apr 16 '14 at 05:07
  • If you want a delay the UI thread will have to be blocked since achieving the delay is your aim. Else you will have do some dummy work by looping, which is a worse option since it does not give you any hold over exact delay achievable. So this is a viable option given your requirements. – SoulRayder Apr 16 '14 at 05:12
  • The proper way to delay things in the UI thread is to post them to a Handler. – Kevin Krumwiede Apr 16 '14 at 08:12
0

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.

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
registerReceiver(broadcastReceiver, intentFilter);

Check the below link for details

Get notified on connectivity change

Community
  • 1
  • 1
Viswanath Lekshmanan
  • 9,945
  • 1
  • 40
  • 64
0
public void mobiledataenable(boolean enabled) {
try { 
        final ConnectivityManager conman = (ConnectivityManager)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);
}
catch (Exception e)
{
    e.printStackTrace();
}     

}

0

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 here
setMobileDataEnabled(getApplicationContext(),true);

Lemme know if i couldn't get you properly!

DiLDoST
  • 335
  • 3
  • 12
-1

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

 public void setMobileDataEnabled(Context context, boolean status) 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, status);
}
Arwy Shelke
  • 333
  • 1
  • 2
  • 12