如果我进入“设置-数据使用情况”并按下“属性”按钮,我可以在使用安卓4.1.2的三星Galaxy S2(i9105P)上激活“限制后台数据”的选项。是否有办法以编程方式开启或关闭此选项?我只想在满足我的应用程序确定的某些条件时才激活/停用它,这样我就不必手动记住要激活它了。PS:我已经在android.developer.com网站上搜索过,但没有找到相关内容。
据我所知,对于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();
}
}
您可以在命令行中运行以下命令:svc data disable
或 svc data enable
。显然,您需要使用root权限才能执行此操作,如下所示:
Runtime.getRuntime().exec("echo svc data disable | su");
如果您的设备已经获取了root权限,则应该会弹出root对话框。