[英]Force an Android app to use mobile data without turning wifi off
我的应用有时需要通过移动数据进行连接才能正常工作。 我知道有些应用程序可以使某个应用程序仅使用移动数据,并且我知道如何使用该应用程序关闭和开启wifi。 但是,是否有一种方法可以告诉我的应用从现在开始使用移动连接,而在另一点取消此限制?
我使用的变通办法仅适用于有根电话。
已从ConnectivityManager中删除了setMobileDataEnabled方法,但为此功能向TelephonyManager中添加了两个方法getDataEnabled和setDataEnabled。
public void setMobileDataState(boolean mobileDataEnabled)
{
try
{
TelephonyManager telephonyService = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
Method setMobileDataEnabledMethod = telephonyService.getClass().getDeclaredMethod("setDataEnabled", boolean.class);
if (null != setMobileDataEnabledMethod)
{
setMobileDataEnabledMethod.invoke(telephonyService, mobileDataEnabled);
}
}
catch (Exception ex)
{
Log.e(TAG, "Error setting mobile data state", ex);
}
}
public boolean getMobileDataState()
{
try
{
TelephonyManager telephonyService = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
Method getMobileDataEnabledMethod = telephonyService.getClass().getDeclaredMethod("getDataEnabled");
if (null != getMobileDataEnabledMethod)
{
boolean mobileDataEnabled = (Boolean) getMobileDataEnabledMethod.invoke(telephonyService);
return mobileDataEnabled;
}
}
catch (Exception ex)
{
Log.e(TAG, "Error getting mobile data state", ex);
}
return false;
}
但是您需要将此权限(MODIFY_PHONE_STATE)添加到清单文件中,否则将收到SecurityException。
您不能显式强制每个应用程序使用通信通道(可以通过ConnectivityManager.setNetworkPreference(...)
请求使用首选模式,但这不是“强制”)。
// and to be sure:
ConnectivityManager.setNetworkPreference(ConnectivityManager.TYPE_MOBILE);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.