简体   繁体   中英

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. 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.

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.

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").

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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