简体   繁体   中英

turn 3g on/off android 4.4 or above

My SDK upgraded and I can not enable or disable 3G with code on Eclipse.

This code doesnt work anymore.

private void setMobileDataEnabled(Context context, boolean enabled) 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, enabled);
}

Applications aren't supposed to turn 3g/4g/GPS on or off by themselves. There were glitches/workarounds that have allowed it but they aren't reliable, since they are getting fixed.

What you should do, is notify the user that their 3g state needs to change, maybe with an AlertDialog , and give them the option to navigate to the phone settings page, via an intent , where they can manually enable 3g.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM