Latest update on enabling and disabling mobile data programmatically

帅比萌擦擦* 提交于 2019-12-17 02:09:19

问题


Although this is a "duplicate", the current answers are out of date and, mostly, no longer apply. I thought it would be good to provide an updated resource here, if possible, to save people time, as I have just done, researching this issue.

I've been googling around to see the latest information on being able to enable and disable mobile data from within an app (if wifi is not available).

This is one of the latest things I can find:
Did you know you can no longer Disable/Enable Data on lollipop from a widget?

There is an answer to that, I quote:

There was never an API for it. Developers were using a workaround by calling the method via Reflections. All Google did was close this "exploit".

There is also this discussion:

Replacement for setMobileDataEnabled() api
Which is Feb 2015.

There are these questions here:

How to disable Mobile Data on Android

This was asked in 2010 and the latest answer was updated with a one liner on Dec 2014.

Enable/disable data connection in android programmatically

And this, the accepted answer in 2012.

What's the latest on this issue?

Can it still be done?


回答1:


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.




回答2:


It wont work on non-rooted phone as they added MODIFY_PHONE_STATE permission check. This permission is only given to system or signature apps refer-here.

Check the code below from PhoneInterfaceManager:

   @Override
   public void setDataEnabled(boolean enable) {
       enforceModifyPermission();
       mPhone.setDataEnabled(enable);
   }
   private void enforceModifyPermission() {
       mApp.enforceCallingOrSelfPermission(android.Manifest.permission.MODIFY_PHONE_STATE, null);
   }



回答3:


Unless you have a rooted phone I don't think you can enable and disable data programmatically because in order to do so we have to include MODIFY_PHONE_STATE permission which is only given to system or signature apps.

setMobileDataEnabled() method is no longer callable via reflection. It was callable since Android 2.1 (API 7) to Android 4.4 (API 19) via reflection, but as of Android 5.0 and later, even with the rooted phones, the setMobileDataEnabled() method is not callable.




回答4:


Fast forward to the end of 2018...

The short answer is it is no longer allowed to enable/disable mobile data programmatically. Here is the solution that I use all the time.

This code opens system data usage settings screen, where the user can disable mobile data manually.

public void enableDisableMobileData() {
    Intent intent = new Intent();
    intent.setComponent(new ComponentName(
        "com.android.settings", 
        "com.android.settings.Settings$DataUsageSummaryActivity"));
    startActivity(intent);
}

EDIT 2019:

The answer above does not work starting on API 28. This is what works:

Intent intent = new Intent(Settings.ACTION_DATA_USAGE_SETTINGS);
startActivity(intent);



回答5:


Easy Method.

public void setMobileDataState(boolean mobileDataEnabled)
{
    try{
        ConnectivityManager dataManager;
        dataManager  = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        Method dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
        dataMtd.setAccessible(true);
        dataMtd.invoke(dataManager, mobileDataEnabled);
    }catch(Exception ex){
        //Error Code Write Here
    }
}


来源:https://stackoverflow.com/questions/31120082/latest-update-on-enabling-and-disabling-mobile-data-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!