Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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!

like image 452
user2933671 Avatar asked Nov 10 '22 09:11

user2933671


1 Answers

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);
like image 83
SoulRayder Avatar answered Nov 14 '22 21:11

SoulRayder