How to disable Mobile Data on Android

后端 未结 8 1863
予麋鹿
予麋鹿 2020-11-22 12:13

Quick back story before someone tells me to buy an app. =)

I just got an EVO and it chews through the battery fairly quick. I downloaded JuiceDefender to manage

8条回答
  •  逝去的感伤
    2020-11-22 12:46

    Starting from 'Gingerbread' you can use the IConnectivityManager.setMobileDataEnabled() method. It's hidden in API, but can be accessed with reflection. http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.2_r1.1/android/net/ConnectivityManager.java#376

    With this method you can change the system setting: 'Settings -> Wireless & network -> Mobile network settings -> Data Enabled'

    Code example:

    private void setMobileDataEnabled(Context context, boolean enabled) {
        final ConnectivityManager conman = (ConnectivityManager) context.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);
    }
    

    Also you need the CHANGE_NETWORK_STATE permission.

    
    

    Needless to say that this approach might not work in future android versions. But I guess that applications such as '3G watchdog', 'APNdroid' or 'DataLock' work this way.


    UPDATE:
    setMobileDataEnabled method is no longer available on Lollipop

提交回复
热议问题