简体   繁体   English

强制Android应用在不关闭wifi的情况下使用移动数据

[英]Force an Android app to use mobile data without turning wifi off

My app sometimes needs to connect via mobile data in order to work. 我的应用有时需要通过移动数据进行连接才能正常工作。 I know there are apps that can make a certain app use only mobile data and I know how I can turn off and on the wifi with my app. 我知道有些应用程序可以使某个应用程序仅使用移动数据,并且我知道如何使用该应用程序关闭和开启wifi。 But is there a way to tell my app to use mobile connection from now on and at another point remove this restriction? 但是,是否有一种方法可以告诉我的应用从现在开始使用移动连接,而在另一点取消此限制?

I use a workaround which only works for rooted phones. 我使用的变通办法仅适用于有根电话。

The setMobileDataEnabled method was removed from the ConnectivityManager but two methods getDataEnabled and setDataEnabled were added to the TelephonyManager for this functionality. 已从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;
}

But you need to add this permission (MODIFY_PHONE_STATE) to the Manifest file otherwise you will get a SecurityException. 但是您需要将此权限(MODIFY_PHONE_STATE)添加到清单文件中,否则将收到SecurityException。

You can't explicitly force the communications channel on a per-app basis (you can request to use a preferred mode via ConnectivityManager.setNetworkPreference(...) , but that's not "forcing"). 您不能显式强制每个应用程序使用通信通道(可以通过ConnectivityManager.setNetworkPreference(...)请求使用首选模式,但这不是“强制”)。

 // and to be sure:
   ConnectivityManager.setNetworkPreference(ConnectivityManager.TYPE_MOBILE);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM