4

If I go to "Settings - Data Usage" and press the "Properties" I can activate "Restrict Background Data", using a Samsung Galaxy S2 (i9105P) with Android 4.1.2.

Is there any way I can do this programmatically, both on and off?

I only want to activate/deactivate it under certain conditions (determined by my app) so I don't have to manually remember to activate it.

PS: I searched the android.developer.com website, but with no success.

4

2 回答 2

0

您可以在命令行中运行此命令, svc data disable或者svc data enable 您显然需要 root 才能执行此操作,如下所示:

Runtime.getRuntime().exec("echo svc data disable | su");

如果您的设备已植根,这应该会弹出根对话框。

于 2015-02-24T19:37:11.453 回答
0

据我所知,对于 Android 4.x,您不能这样做。只有猴子跑步者插件可以帮助你。

但如果您需要 Android 2.x,这是我使用的方法:

/**
 * Switch mobile data network access 
 * */

public void nmSwitchMobileNetworkDataAccess(boolean swtichCellOn){

    boolean disable;
    TelephonyManager telephonyManager = (TelephonyManager)m_context.getSystemService(Context.TELEPHONY_SERVICE);

    if(telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED){
        disable = false;
    }else{
        disable = true;  
    }

    try{
        final ConnectivityManager conman = (ConnectivityManager)m_context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        final Method setMobileDataEnabledMethod = conman.getClass().getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);

        if(disable == true && swtichCellOn == true){
            setMobileDataEnabledMethod.invoke(conman, true);//turn cell on

            DispatcherAndroid.androidObserverItf.androidObserver_OnProgress("Turn cell on, done",
                    EMethodResponse.ON_NM_REQ.FromEnumToString()  );
        }
        else if(disable == false && swtichCellOn == false){
            setMobileDataEnabledMethod.invoke(conman, false);//turn cell off

            DispatcherAndroid.androidObserverItf.androidObserver_OnProgress("Turn cell off, done",
                    EMethodResponse.ON_NM_REQ.FromEnumToString()  );
        }   
        else if((disable == false && swtichCellOn == true) || (disable == true && swtichCellOn == false)){
            DispatcherAndroid.androidObserverItf.androidObserver_OnProgress("No changes",
                    EMethodResponse.ON_NM_REQ.FromEnumToString()  );
        }

    }
    catch(Exception e){
        e.printStackTrace();
    }
}
于 2013-09-08T12:05:02.543 回答