0

I am working on an app where I need to turn mobile data after interval of 2 hours. But in devices which are above marshmallow its not working.I am not able to toggle the mobile data from the app.

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;
}

Above method only worked for rooted devices. I also tried other way of doing it, but no luck. If any one have achieved this. Then please suggest something would be great help.

itsmysterybox
  • 2,748
  • 3
  • 21
  • 26
Danial clarc
  • 724
  • 1
  • 7
  • 25
  • there is no way and should be no way to turn mobile data on for 3rd-party apps. The explaination is simple: your user is in roaming in another country, and has mobile data turned off. Then your app turns it on, uses a lot of mobile data, your user gets charged by mobile provider for a thousand $. – Vladyslav Matviienko Oct 02 '18 at 07:16
  • App is for reducing human efforts ,I am giving an option to turn mobile data manually or automatically . – Danial clarc Oct 02 '18 at 07:38
  • 1
    that is not a matter of your app, it is a matter of 3rd-party apps in general. None of them should be able to turn mobile data on, if user has turned it off. It is regardless of how good or bad your app is, whether it has advanced logic to prevent user being charged or not, or any other case. There is no way and should be no way to do that. – Vladyslav Matviienko Oct 02 '18 at 07:53
  • I think this is somehow connected to Android Permissions – Anton Kazakov Oct 02 '18 at 08:08
  • yes it is ."android.permission.MODIFY_PHONE_STATE","android.permission.WRITE_SETTINGS" , but both permissions are protected permissions ,which are only given to system apps. – Danial clarc Oct 02 '18 at 08:12

0 Answers0