سؤال

I'm building an android application that will use a Switch widget to enable/disable the data connection of the device.

My problem is actually the data roaming: if the user has disabled the data connection roaming, then the API methods such NetworkInfo.isConnectedOrConnecting() or TelephoneManager.getDataState() will say that the connection is off.

In general this is true, but in my context this is false if the data connection is "ticked" from the android settings.

So, I need a method that can check if the data connection is ticked, instead of enabled/active/etc.

Any idea?

هل كانت مفيدة؟

المحلول

Define "mobile_data" row name, where the system stores the data connection checkbox/switch's state, locally:

private static final String MOBILE_DATA = "mobile_data";

And check if the value of that row is 0 or not. If it is 0, then the data connection is unchecked/disabled (un-ticked):

private boolean isMobileDataChecked() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        // The row has been moved to 'global' table in API level 17
        return Settings.Global.getInt(getContentResolver(), MOBILE_DATA, 0) != 0;
    }

    try {
        // It was in 'secure' table before
        int enabled = Settings.Secure.getInt(getContentResolver(), MOBILE_DATA);
        return enabled != 0;
    } catch (SettingNotFoundException e) {
        // It was in 'system' table originally, but I don't remember when that was the case.
        // So, probably, you won't need all these try/catches.
        // But, hey, it is better to be safe than sorry :)
        return Settings.System.getInt(getContentResolver(), MOBILE_DATA, 0) != 0;
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top