Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit c3b80d6a authored by TreeHugger Robot's avatar TreeHugger Robot Committed by Android (Google) Code Review
Browse files

Merge "Refactor ConfigureWifiSettings for better testing"

parents 8cc6f9f7 925f2324
Loading
Loading
Loading
Loading
+65 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.settings.wifi;

import android.content.Context;
import android.provider.Settings;
import android.support.v14.preference.SwitchPreference;
import android.support.v7.preference.Preference;
import android.text.TextUtils;

import com.android.settings.core.PreferenceController;

public class AllowRecommendationPreferenceController extends PreferenceController {

    private static final String KEY_ALLOW_RECOMMENDATIONS = "allow_recommendations";

    public AllowRecommendationPreferenceController(Context context) {
        super(context);
    }

    @Override
    public boolean isAvailable() {
        return true;
    }

    @Override
    public void updateState(Preference preference) {
        ((SwitchPreference) preference).setChecked(Settings.Global.getInt(
                mContext.getContentResolver(),
                Settings.Global.NETWORK_RECOMMENDATIONS_ENABLED, 0) == 1);
    }

    @Override
    public boolean handlePreferenceTreeClick(Preference preference) {
        if (!TextUtils.equals(preference.getKey(), KEY_ALLOW_RECOMMENDATIONS)) {
            return false;
        }
        if (!(preference instanceof SwitchPreference)) {
            return false;
        }
        Settings.Global.putInt(mContext.getContentResolver(),
                Settings.Global.NETWORK_RECOMMENDATIONS_ENABLED,
                ((SwitchPreference) preference).isChecked() ? 1 : 0);
        return true;
    }

    @Override
    public String getPreferenceKey() {
        return KEY_ALLOW_RECOMMENDATIONS;
    }
}
+85 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.settings.wifi;

import android.content.Context;
import android.provider.Settings;
import android.support.v14.preference.SwitchPreference;
import android.support.v7.preference.Preference;
import android.text.TextUtils;

import com.android.settings.core.PreferenceController;

/**
 * {@link PreferenceController} that controls whether we should fall back to celluar when wifi is
 * bad.
 */
public class CellularFallbackPreferenceController extends PreferenceController {

    private static final String KEY_CELLULAR_FALLBACK = "wifi_cellular_data_fallback";


    public CellularFallbackPreferenceController(Context context) {
        super(context);
    }

    @Override
    public boolean isAvailable() {
        return !avoidBadWifiConfig();
    }

    @Override
    public String getPreferenceKey() {
        return KEY_CELLULAR_FALLBACK;
    }

    @Override
    public boolean handlePreferenceTreeClick(Preference preference) {
        if (!TextUtils.equals(preference.getKey(), KEY_CELLULAR_FALLBACK)) {
            return false;
        }
        if (!(preference instanceof SwitchPreference)) {
            return false;
        }
        // On: avoid bad wifi. Off: prompt.
        String settingName = Settings.Global.NETWORK_AVOID_BAD_WIFI;
        Settings.Global.putString(mContext.getContentResolver(), settingName,
                ((SwitchPreference) preference).isChecked() ? "1" : null);
        return true;
    }

    @Override
    public void updateState(Preference preference) {
        final boolean currentSetting = avoidBadWifiCurrentSettings();
        // TODO: can this ever be null? The return value of avoidBadWifiConfig() can only
        // change if the resources change, but if that happens the activity will be recreated...
        if (preference != null) {
            SwitchPreference pref = (SwitchPreference) preference;
            pref.setChecked(currentSetting);
        }
    }

    private boolean avoidBadWifiConfig() {
        return mContext.getResources().getInteger(
                com.android.internal.R.integer.config_networkAvoidBadWifi) == 1;
    }

    private boolean avoidBadWifiCurrentSettings() {
        return "1".equals(Settings.Global.getString(mContext.getContentResolver(),
                Settings.Global.NETWORK_AVOID_BAD_WIFI));
    }
}
+28 −194
Original line number Diff line number Diff line
@@ -15,222 +15,56 @@
 */
package com.android.settings.wifi;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v14.preference.SwitchPreference;
import android.support.v7.preference.ListPreference;
import android.support.v7.preference.Preference;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.settings.R;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.Utils;
import com.android.settings.core.PreferenceController;
import com.android.settings.dashboard.DashboardFragment;

import java.util.ArrayList;
import java.util.List;

public class ConfigureWifiSettings extends SettingsPreferenceFragment
        implements Preference.OnPreferenceChangeListener {
    private static final String TAG = "ConfigureWifiSettings";
import static android.content.Context.WIFI_SERVICE;

    private static final String KEY_MAC_ADDRESS = "mac_address";
    private static final String KEY_SAVED_NETWORKS = "saved_networks";
    private static final String KEY_CURRENT_IP_ADDRESS = "current_ip_address";
    private static final String KEY_NOTIFY_OPEN_NETWORKS = "notify_open_networks";
    private static final String KEY_SLEEP_POLICY = "sleep_policy";
    private static final String KEY_CELLULAR_FALLBACK = "wifi_cellular_data_fallback";
    private static final String KEY_ALLOW_RECOMMENDATIONS = "allow_recommendations";
public class ConfigureWifiSettings extends DashboardFragment {

    private WifiManager mWifiManager;
    private IntentFilter mFilter;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        addPreferencesFromResource(R.xml.wifi_configure_settings);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        mFilter = new IntentFilter();
        mFilter.addAction(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION);
        mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    }
    private static final String TAG = "ConfigureWifiSettings";

    @Override
    public void onResume() {
        super.onResume();
        initPreferences();
        getActivity().registerReceiver(mReceiver, mFilter);
        refreshWifiInfo();
    }
    private WifiManager mWifiManager;

    @Override
    public void onPause() {
        super.onPause();
        getActivity().unregisterReceiver(mReceiver);
    }

    private void initPreferences() {
        List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks();
        if (configs == null || configs.size() == 0) {
            removePreference(KEY_SAVED_NETWORKS);
        }

        SwitchPreference notifyOpenNetworks =
                (SwitchPreference) findPreference(KEY_NOTIFY_OPEN_NETWORKS);
        notifyOpenNetworks.setChecked(Settings.Global.getInt(getContentResolver(),
                Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0) == 1);
        notifyOpenNetworks.setEnabled(mWifiManager.isWifiEnabled());

        final Context context = getActivity();
        if (avoidBadWifiConfig()) {
            // Hide preference toggle, always avoid bad wifi networks.
            removePreference(KEY_CELLULAR_FALLBACK);
        } else {
            // Show preference toggle, initialized based on current settings value.
            boolean currentSetting = avoidBadWifiCurrentSettings();
            SwitchPreference pref = (SwitchPreference) findPreference(KEY_CELLULAR_FALLBACK);
            // TODO: can this ever be null? The return value of avoidBadWifiConfig() can only
            // change if the resources change, but if that happens the activity will be recreated...
            if (pref != null) {
                pref.setChecked(currentSetting);
            }
        }

        SwitchPreference allowRecommendations =
            (SwitchPreference) findPreference(KEY_ALLOW_RECOMMENDATIONS);
        allowRecommendations.setChecked(Settings.Global.getInt(getContentResolver(),
            Settings.Global.NETWORK_RECOMMENDATIONS_ENABLED, 0) == 1);

        ListPreference sleepPolicyPref = (ListPreference) findPreference(KEY_SLEEP_POLICY);
        if (sleepPolicyPref != null) {
            if (Utils.isWifiOnly(context)) {
                sleepPolicyPref.setEntries(R.array.wifi_sleep_policy_entries_wifi_only);
            }
            sleepPolicyPref.setOnPreferenceChangeListener(this);
            int value = Settings.Global.getInt(getContentResolver(),
                    Settings.Global.WIFI_SLEEP_POLICY,
                    Settings.Global.WIFI_SLEEP_POLICY_NEVER);
            String stringValue = String.valueOf(value);
            sleepPolicyPref.setValue(stringValue);
            updateSleepPolicySummary(sleepPolicyPref, stringValue);
        }
    }

    private void updateSleepPolicySummary(Preference sleepPolicyPref, String value) {
        if (value != null) {
            String[] values = getResources().getStringArray(R.array.wifi_sleep_policy_values);
            final int summaryArrayResId = Utils.isWifiOnly(getActivity()) ?
                    R.array.wifi_sleep_policy_entries_wifi_only : R.array.wifi_sleep_policy_entries;
            String[] summaries = getResources().getStringArray(summaryArrayResId);
            for (int i = 0; i < values.length; i++) {
                if (value.equals(values[i])) {
                    if (i < summaries.length) {
                        sleepPolicyPref.setSummary(summaries[i]);
                        return;
                    }
                }
            }
        }

        sleepPolicyPref.setSummary("");
        Log.e(TAG, "Invalid sleep policy value: " + value);
    }

    private boolean avoidBadWifiConfig() {
        return getActivity().getResources().getInteger(
                com.android.internal.R.integer.config_networkAvoidBadWifi) == 1;
    }

    private boolean avoidBadWifiCurrentSettings() {
        return "1".equals(Settings.Global.getString(getContentResolver(),
                Settings.Global.NETWORK_AVOID_BAD_WIFI));
    public int getMetricsCategory() {
        return MetricsEvent.CONFIGURE_WIFI;
    }

    @Override
    public boolean onPreferenceTreeClick(Preference preference) {
        String key = preference.getKey();

        if (KEY_NOTIFY_OPEN_NETWORKS.equals(key)) {
            Settings.Global.putInt(getContentResolver(),
                    Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON,
                    ((SwitchPreference) preference).isChecked() ? 1 : 0);
        } else if (KEY_CELLULAR_FALLBACK.equals(key)) {
            // On: avoid bad wifi. Off: prompt.
            String settingName = Settings.Global.NETWORK_AVOID_BAD_WIFI;
            Settings.Global.putString(getContentResolver(), settingName,
                    ((SwitchPreference) preference).isChecked() ? "1" : null);
        } else if (KEY_ALLOW_RECOMMENDATIONS.equals(key)) {
            Settings.Global.putInt(getActivity().getContentResolver(),
                Settings.Global.NETWORK_RECOMMENDATIONS_ENABLED,
                ((SwitchPreference) preference).isChecked() ? 1 : 0);
        } else {
            return super.onPreferenceTreeClick(preference);
        }
        return true;
    protected String getCategoryKey() {
        // We don't want to inject any external settings into this screen.
        return null;
    }

    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        final Context context = getActivity();
        String key = preference.getKey();

        if (KEY_SLEEP_POLICY.equals(key)) {
            try {
                String stringValue = (String) newValue;
                Settings.Global.putInt(getContentResolver(), Settings.Global.WIFI_SLEEP_POLICY,
                        Integer.parseInt(stringValue));
                updateSleepPolicySummary(preference, stringValue);
            } catch (NumberFormatException e) {
                Toast.makeText(context, R.string.wifi_setting_sleep_policy_error,
                        Toast.LENGTH_SHORT).show();
                return false;
            }
        }

        return true;
    }

    private void refreshWifiInfo() {
        final Context context = getActivity();
        WifiInfo wifiInfo = mWifiManager.getConnectionInfo();

        Preference wifiMacAddressPref = findPreference(KEY_MAC_ADDRESS);
        String macAddress = wifiInfo == null ? null : wifiInfo.getMacAddress();
        wifiMacAddressPref.setSummary(!TextUtils.isEmpty(macAddress) ? macAddress
                : context.getString(R.string.status_unavailable));
        wifiMacAddressPref.setSelectable(false);

        Preference wifiIpAddressPref = findPreference(KEY_CURRENT_IP_ADDRESS);
        String ipAddress = Utils.getWifiIpAddresses(context);
        wifiIpAddressPref.setSummary(ipAddress == null ?
                context.getString(R.string.status_unavailable) : ipAddress);
        wifiIpAddressPref.setSelectable(false);
    protected String getLogTag() {
        return TAG;
    }

    @Override
    public int getMetricsCategory() {
        return MetricsEvent.CONFIGURE_WIFI;
    protected int getPreferenceScreenResId() {
        return R.xml.wifi_configure_settings;
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION) ||
                action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                refreshWifiInfo();
            }
    protected List<PreferenceController> getPreferenceControllers(Context context) {
        mWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
        final List<PreferenceController> controllers = new ArrayList<>();
        controllers.add(new WifiInfoPreferenceController(context, getLifecycle(), mWifiManager));
        controllers.add(new SavedNetworkPreferenceController(context, mWifiManager));
        controllers.add(new NotifyOpenNetworksPreferenceController(context, mWifiManager));
        controllers.add(new CellularFallbackPreferenceController(context));
        controllers.add(new AllowRecommendationPreferenceController(context));
        controllers.add(new WifiSleepPolicyPreferenceController(context));
        return controllers;
    }
    };
}
+76 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.settings.wifi;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.support.v14.preference.SwitchPreference;
import android.support.v7.preference.Preference;
import android.text.TextUtils;

import com.android.settings.core.PreferenceController;

/**
 * {@link PreferenceController} that controls whether we should notify user when open network is
 * available.
 */
public class NotifyOpenNetworksPreferenceController extends PreferenceController {

    private static final String KEY_NOTIFY_OPEN_NETWORKS = "notify_open_networks";
    private final WifiManager mWifiManager;

    public NotifyOpenNetworksPreferenceController(Context context, WifiManager wifiManager) {
        super(context);
        mWifiManager = wifiManager;
    }

    @Override
    public boolean isAvailable() {
        return true;
    }

    @Override
    public boolean handlePreferenceTreeClick(Preference preference) {
        if (!TextUtils.equals(preference.getKey(), KEY_NOTIFY_OPEN_NETWORKS)) {
            return false;
        }
        if (!(preference instanceof SwitchPreference)) {
            return false;
        }
        Settings.Global.putInt(mContext.getContentResolver(),
                Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON,
                ((SwitchPreference) preference).isChecked() ? 1 : 0);
        return true;
    }

    @Override
    public String getPreferenceKey() {
        return KEY_NOTIFY_OPEN_NETWORKS;
    }

    @Override
    public void updateState(Preference preference) {
        if (!(preference instanceof SwitchPreference)) {
            return;
        }
        final SwitchPreference notifyOpenNetworks = (SwitchPreference) preference;
        notifyOpenNetworks.setChecked(Settings.Global.getInt(mContext.getContentResolver(),
                Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0) == 1);
        notifyOpenNetworks.setEnabled(mWifiManager.isWifiEnabled());
    }
}
+51 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.settings.wifi;

import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;

import com.android.settings.core.PreferenceController;

import java.util.List;

/**
 * {@link PreferenceController} that opens saved network subsetting.
 */
public class SavedNetworkPreferenceController extends PreferenceController {

    private static final String KEY_SAVED_NETWORKS = "saved_networks";

    private final WifiManager mWifiManager;

    public SavedNetworkPreferenceController(Context context, WifiManager wifiManager) {
        super(context);
        mWifiManager = wifiManager;
    }

    @Override
    public boolean isAvailable() {
        final List<WifiConfiguration> config = mWifiManager.getConfiguredNetworks();
        return config != null && !config.isEmpty();
    }

    @Override
    public String getPreferenceKey() {
        return KEY_SAVED_NETWORKS;
    }
}
Loading