【问题标题】:Detecting programmatically if "Restrict background data" is enabled for Android app以编程方式检测是否为 Android 应用启用了“限制后台数据”
【发布时间】:2016-06-27 17:11:48
【问题描述】:

我搜索了堆栈溢出,但找不到为我的应用检测此设置的答案。在 Android Marshmallow 中,设置中有一个选项:

设置 -> 数据使用 -> 我的应用程序 -> 切换“限制应用程序后台数据”,即“禁用蜂窝网络上的后台数据”

如果在我的应用中设置了此项,我想警告用户。如何检测是否为我的应用设置了此项。任何指针表示赞赏。

【问题讨论】:

  • 找到解决方案了吗?
  • 另外,我如何确定后台数据是否已针对整个手机或仅针对我的应用程序禁用?

标签: android background-process


【解决方案1】:

根据从 Android 7.0(API 级别 24)开始的最新 android 文档...

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

监控流量节省程序首选项的更改 应用可以通过创建一个 BroadcastReceiver 来监听 Co​​nnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED 并使用 Context.registerReceiver() 动态注册接收器来监控 Data Saver 首选项的变化。当应用收到此广播时,应通过调用 ConnectivityManager.getRestrictBackgroundStatus() 检查新的数据保护程序首选项是否影响其权限。

注意:系统只会将此广播发送给使用 Context.registerReceiver() 动态注册它们的应用程序。在清单中注册接收此广播的应用将不会收到它们。

【讨论】:

    【解决方案2】:

    你可以使用getActiveNetworkInfo()

    当后台数据不可用时,getActiveNetworkInfo() 现在将 似乎已断开连接。

    Reference

    仅供参考:

    根据Android参考,getBackgroundDataSetting

    返回后台数据使用设置的值。如果是假的, 如果应用程序不在网络中,则应用程序不应使用网络 前景。

    但是这在 API 级别 14 中已被弃用。

    【讨论】:

    • getActiveNetworkInfo() 的问题是当你在 wifi 上时它是连接的。它不会告诉您该应用程序是否为 Cellular 禁用了后台设置.. :(
    猜你喜欢
    • 2015-05-13
    • 2012-09-19
    • 2014-02-15
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多