Tuesday, October 25, 2011

How to enable/disable Mobile Data on Android 2.3

Today, colleague asked me whether i know how to enable and disable mobile internet on Android ? Actually, I was curious about this for sometime and never had the time to look into how to do this. So this is how to do it.

I tired it on Android 2.3 i tried this code and it worked! When I looked into Android source code I saw this method is available 2.2 R1 up.


  private boolean getMobileDataEnabled() {
        try {
            Method method = connectivityManager.getClass().getMethod("getMobileDataEnabled");
            return (Boolean)method.invoke(connectivityManager);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    private void setMobileDataEnabled(boolean on) {
        try {
            Method method = connectivityManager.getClass().getMethod("setMobileDataEnabled",
                    boolean.class);
            method.invoke(connectivityManager, on);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
If you are using 2.2 R1 or later try this code.


8 comments:

  1. Good catch. Thanks for sharing

    ReplyDelete
  2. hi could u share your full code of that?
    i have tried it in my emulator and it gave me java.lang.reflect.IncocationTargetException.
    please reply my comment. thx

    ReplyDelete
  3. thanks for sharing , i want this code in my inbox : java.lok2011@gmail.com

    ReplyDelete
  4. Method method = connectivityManager.getClass().getMethod("setMobileDataEnabled", boolean.class);
    =========================
    what is connectivityManager

    ReplyDelete
    Replies
    1. ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

      Delete
  5. This comment has been removed by the author.

    ReplyDelete
  6. I used this code.
    I got exception on method invoke

    ReplyDelete