Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting programmatically if "Restrict background data" is enabled for Android app

I searched stack overflow and could not find an answer to detect this setting set for my app. In Android Marshmallow there is an option in Settings :

Settings -> Data Usage -> My App -> Toggle for "Restrict app background data" which "disable background data on cellular network"

I want to warn the user if this set in my app. How can I detect if this is set for my app. Any pointers appreciated.

like image 539
user3570727 Avatar asked Jun 27 '16 17:06

user3570727


People also ask

What happens if I restrict app background data?

It will use the internet only when you open an app. This even means you won't get real-time updates and notifications when the app is closed. You can easily restrict the background data on your Android and iOS devices in a few simple steps.


1 Answers

Per the latest android docs starting with Android 7.0 (API level 24)...

https://developer.android.com/training/basics/network-ops/data-saver.html

ConnectivityManager connMgr = (ConnectivityManager)
    getSystemService(Context.CONNECTIVITY_SERVICE);
// Checks if the device is on a metered network
if (connMgr.isActiveNetworkMetered()) {
  // Checks user’s Data Saver settings.
  switch (connMgr.getRestrictBackgroundStatus()) {
    case RESTRICT_BACKGROUND_STATUS_ENABLED:
    // Background data usage is blocked for this app. Wherever possible,
    // the app should also use less data in the foreground.

    case RESTRICT_BACKGROUND_STATUS_WHITELISTED:
    // The app is whitelisted. Wherever possible,
    // the app should use less data in the foreground and background.

    case RESTRICT_BACKGROUND_STATUS_DISABLED:
    // Data Saver is disabled. Since the device is connected to a
    // metered network, the app should use less data wherever possible.
  }
} else {
  // The device is not on a metered network.
  // Use data as required to perform syncs, downloads, and updates.
}

Monitoring Changes to Data Saver Preferences Apps can monitor changes to Data Saver preferences by creating a BroadcastReceiver to listen for ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED and dynamically registering the receiver with Context.registerReceiver(). When an app receives this broadcast, it should check if the new Data Saver preferences affect its permissions by calling ConnectivityManager.getRestrictBackgroundStatus().

Note: The system only sends this broadcast to apps that dynamically register for them with Context.registerReceiver(). Apps that register to receive this broadcast in their manifest will not receive them.

like image 173
Tom Bollwitt Avatar answered Nov 14 '22 23:11

Tom Bollwitt