0

我正在构建一个必须在后台保持 Wi-Fi 连接处于活动状态的应用程序。因此,当设备进入睡眠状态时,设备不会自动关闭 Wi-Fi,这一点很重要。

因此,我想检查设备上当前的 Wi-Fi 睡眠策略,如果它是错误的,我想通知用户并将其链接到正确的设置页面,以便他们可以更改它。

为了做到这一点,我编写了以下代码:

@SuppressWarnings("deprecation")
@SuppressLint({ "InlinedApi", "NewApi" })
private void checkWiFiPolicy() {
    ContentResolver cr = this.getContentResolver();
    int apiLevel = 0;
    try { apiLevel = Build.VERSION.SDK_INT; } catch (Exception e) {}

    int apiIndWifiSleepPolicyDefault = -1;
    int apiIndWifiSleepPolicyNever = -1;
    int apiIndWifiSleepPolicyNeverWhilePlugged = -1;
    int currentWifiPolicy = -10;
    if (apiLevel < 17) {
        apiIndWifiSleepPolicyDefault = Settings.System.WIFI_SLEEP_POLICY_DEFAULT;
        apiIndWifiSleepPolicyNever = Settings.System.WIFI_SLEEP_POLICY_NEVER;
        apiIndWifiSleepPolicyNeverWhilePlugged = Settings.System.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED;
        try {
            currentWifiPolicy = Settings.System.getInt(cr, android.provider.Settings.System.WIFI_SLEEP_POLICY);
        } catch (Exception e) {}
    } else {
        apiIndWifiSleepPolicyDefault = Settings.Global.WIFI_SLEEP_POLICY_DEFAULT;
        apiIndWifiSleepPolicyNever = Settings.Global.WIFI_SLEEP_POLICY_NEVER;
        apiIndWifiSleepPolicyNeverWhilePlugged = Settings.Global.WIFI_SLEEP_POLICY_NEVER_WHILE_PLUGGED;
        try {
            currentWifiPolicy = Settings.Global.getInt(cr, android.provider.Settings.Global.WIFI_SLEEP_POLICY);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    if (currentWifiPolicy == apiIndWifiSleepPolicyDefault) {
        ALog.d(ALog.TAG_ACTIVITY, "Detected WifiSleepPolicy: DEFAULT");
    } else if (currentWifiPolicy == apiIndWifiSleepPolicyNever) {
        ALog.d(ALog.TAG_ACTIVITY, "Detected WifiSleepPolicy: NEVER");
    } else if (currentWifiPolicy == apiIndWifiSleepPolicyNeverWhilePlugged) {
        ALog.d(ALog.TAG_ACTIVITY, "Detected WifiSleepPolicy: NEVER WHILE PLUGGED");
    } else {
        ALog.d(ALog.TAG_ACTIVITY, "Detected WifiSleepPolicy: UNKNOWN");
    }
}

但是,此代码在 Nexus 7(Android 4.3,第 1 代)上失败:

W/System.err(5318): android.provider.Settings$SettingNotFoundException: wifi_sleep_policy

即使我尝试使用旧方法(用于 apiLevel < 17 的方法),我也会得到完全相同的错误。(请注意,我可以读取其他系统设置,例如 System.Global.DATA_ROAMING)

关于如何在 Nexus 7 上阅读此设置的任何想法?

4

0 回答 0