以编程方式切换“限制背景数据" [英] Programmatically toggle "Restrict Background Data"

查看:107
本文介绍了以编程方式切换“限制背景数据"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我转到设置-数据使用情况"并按属性",则可以使用Android 4.1.2.的Samsung Galaxy S2(i9105P)激活限制背景数据".

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:我搜索了android.developer.com网站,但没有成功.

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

推荐答案

据我所知,对于Android 4.x,您无法做到这一点.只有MonkeyRunner插件可以帮助您.

As I know for Android 4.x you cant do that. Only monkey runner plugin can help you.

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

But if you need for Android 2.x, this is method I used:

/**
 * 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();
    }
}

这篇关于以编程方式切换“限制背景数据"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆