ConfigureWifiSettings.java revision 66e6027da0455e572ffb517fa36d9dc61f0a62cc
1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.android.settings.wifi;
17
18import android.content.BroadcastReceiver;
19import android.content.Context;
20import android.content.Intent;
21import android.content.IntentFilter;
22import android.net.wifi.WifiConfiguration;
23import android.net.wifi.WifiInfo;
24import android.net.wifi.WifiManager;
25import android.os.Bundle;
26import android.provider.Settings;
27import android.support.v14.preference.SwitchPreference;
28import android.support.v7.preference.ListPreference;
29import android.support.v7.preference.Preference;
30import android.text.TextUtils;
31import android.util.Log;
32import android.widget.Toast;
33import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
34import com.android.settings.R;
35import com.android.settings.SettingsPreferenceFragment;
36import com.android.settings.Utils;
37import java.util.List;
38
39public class ConfigureWifiSettings extends SettingsPreferenceFragment
40        implements Preference.OnPreferenceChangeListener {
41    private static final String TAG = "ConfigureWifiSettings";
42
43    private static final String KEY_MAC_ADDRESS = "mac_address";
44    private static final String KEY_SAVED_NETWORKS = "saved_networks";
45    private static final String KEY_CURRENT_IP_ADDRESS = "current_ip_address";
46    private static final String KEY_NOTIFY_OPEN_NETWORKS = "notify_open_networks";
47    private static final String KEY_SLEEP_POLICY = "sleep_policy";
48    private static final String KEY_CELLULAR_FALLBACK = "wifi_cellular_data_fallback";
49    private static final String KEY_ALLOW_RECOMMENDATIONS = "allow_recommendations";
50
51    private WifiManager mWifiManager;
52    private IntentFilter mFilter;
53
54    @Override
55    public void onCreate(Bundle icicle) {
56        super.onCreate(icicle);
57        addPreferencesFromResource(R.xml.wifi_configure_settings);
58    }
59
60    @Override
61    public void onActivityCreated(Bundle savedInstanceState) {
62        super.onActivityCreated(savedInstanceState);
63        mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
64        mFilter = new IntentFilter();
65        mFilter.addAction(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION);
66        mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
67    }
68
69    @Override
70    public void onResume() {
71        super.onResume();
72        initPreferences();
73        getActivity().registerReceiver(mReceiver, mFilter);
74        refreshWifiInfo();
75    }
76
77    @Override
78    public void onPause() {
79        super.onPause();
80        getActivity().unregisterReceiver(mReceiver);
81    }
82
83    private void initPreferences() {
84        List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks();
85        if (configs == null || configs.size() == 0) {
86            removePreference(KEY_SAVED_NETWORKS);
87        }
88
89        SwitchPreference notifyOpenNetworks =
90                (SwitchPreference) findPreference(KEY_NOTIFY_OPEN_NETWORKS);
91        notifyOpenNetworks.setChecked(Settings.Global.getInt(getContentResolver(),
92                Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0) == 1);
93        notifyOpenNetworks.setEnabled(mWifiManager.isWifiEnabled());
94
95        final Context context = getActivity();
96        if (avoidBadWifiConfig()) {
97            // Hide preference toggle, always avoid bad wifi networks.
98            removePreference(KEY_CELLULAR_FALLBACK);
99        } else {
100            // Show preference toggle, initialized based on current settings value.
101            boolean currentSetting = avoidBadWifiCurrentSettings();
102            SwitchPreference pref = (SwitchPreference) findPreference(KEY_CELLULAR_FALLBACK);
103            // TODO: can this ever be null? The return value of avoidBadWifiConfig() can only
104            // change if the resources change, but if that happens the activity will be recreated...
105            if (pref != null) {
106                pref.setChecked(currentSetting);
107            }
108        }
109
110        SwitchPreference allowRecommendations =
111            (SwitchPreference) findPreference(KEY_ALLOW_RECOMMENDATIONS);
112        allowRecommendations.setChecked(Settings.Global.getInt(getContentResolver(),
113            Settings.Global.NETWORK_RECOMMENDATIONS_ENABLED, 0) == 1);
114
115        ListPreference sleepPolicyPref = (ListPreference) findPreference(KEY_SLEEP_POLICY);
116        if (sleepPolicyPref != null) {
117            if (Utils.isWifiOnly(context)) {
118                sleepPolicyPref.setEntries(R.array.wifi_sleep_policy_entries_wifi_only);
119            }
120            sleepPolicyPref.setOnPreferenceChangeListener(this);
121            int value = Settings.Global.getInt(getContentResolver(),
122                    Settings.Global.WIFI_SLEEP_POLICY,
123                    Settings.Global.WIFI_SLEEP_POLICY_NEVER);
124            String stringValue = String.valueOf(value);
125            sleepPolicyPref.setValue(stringValue);
126            updateSleepPolicySummary(sleepPolicyPref, stringValue);
127        }
128    }
129
130    private void updateSleepPolicySummary(Preference sleepPolicyPref, String value) {
131        if (value != null) {
132            String[] values = getResources().getStringArray(R.array.wifi_sleep_policy_values);
133            final int summaryArrayResId = Utils.isWifiOnly(getActivity()) ?
134                    R.array.wifi_sleep_policy_entries_wifi_only : R.array.wifi_sleep_policy_entries;
135            String[] summaries = getResources().getStringArray(summaryArrayResId);
136            for (int i = 0; i < values.length; i++) {
137                if (value.equals(values[i])) {
138                    if (i < summaries.length) {
139                        sleepPolicyPref.setSummary(summaries[i]);
140                        return;
141                    }
142                }
143            }
144        }
145
146        sleepPolicyPref.setSummary("");
147        Log.e(TAG, "Invalid sleep policy value: " + value);
148    }
149
150    private boolean avoidBadWifiConfig() {
151        return getActivity().getResources().getInteger(
152                com.android.internal.R.integer.config_networkAvoidBadWifi) == 1;
153    }
154
155    private boolean avoidBadWifiCurrentSettings() {
156        return "1".equals(Settings.Global.getString(getContentResolver(),
157                Settings.Global.NETWORK_AVOID_BAD_WIFI));
158    }
159
160    @Override
161    public boolean onPreferenceTreeClick(Preference preference) {
162        String key = preference.getKey();
163
164        if (KEY_NOTIFY_OPEN_NETWORKS.equals(key)) {
165            Settings.Global.putInt(getContentResolver(),
166                    Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON,
167                    ((SwitchPreference) preference).isChecked() ? 1 : 0);
168        } else if (KEY_CELLULAR_FALLBACK.equals(key)) {
169            // On: avoid bad wifi. Off: prompt.
170            String settingName = Settings.Global.NETWORK_AVOID_BAD_WIFI;
171            Settings.Global.putString(getContentResolver(), settingName,
172                    ((SwitchPreference) preference).isChecked() ? "1" : null);
173        } else if (KEY_ALLOW_RECOMMENDATIONS.equals(key)) {
174            Settings.Global.putInt(getActivity().getContentResolver(),
175                Settings.Global.NETWORK_RECOMMENDATIONS_ENABLED,
176                ((SwitchPreference) preference).isChecked() ? 1 : 0);
177        } else {
178            return super.onPreferenceTreeClick(preference);
179        }
180        return true;
181    }
182
183    @Override
184    public boolean onPreferenceChange(Preference preference, Object newValue) {
185        final Context context = getActivity();
186        String key = preference.getKey();
187
188        if (KEY_SLEEP_POLICY.equals(key)) {
189            try {
190                String stringValue = (String) newValue;
191                Settings.Global.putInt(getContentResolver(), Settings.Global.WIFI_SLEEP_POLICY,
192                        Integer.parseInt(stringValue));
193                updateSleepPolicySummary(preference, stringValue);
194            } catch (NumberFormatException e) {
195                Toast.makeText(context, R.string.wifi_setting_sleep_policy_error,
196                        Toast.LENGTH_SHORT).show();
197                return false;
198            }
199        }
200
201        return true;
202    }
203
204    private void refreshWifiInfo() {
205        final Context context = getActivity();
206        WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
207
208        Preference wifiMacAddressPref = findPreference(KEY_MAC_ADDRESS);
209        String macAddress = wifiInfo == null ? null : wifiInfo.getMacAddress();
210        wifiMacAddressPref.setSummary(!TextUtils.isEmpty(macAddress) ? macAddress
211                : context.getString(R.string.status_unavailable));
212        wifiMacAddressPref.setSelectable(false);
213
214        Preference wifiIpAddressPref = findPreference(KEY_CURRENT_IP_ADDRESS);
215        String ipAddress = Utils.getWifiIpAddresses(context);
216        wifiIpAddressPref.setSummary(ipAddress == null ?
217                context.getString(R.string.status_unavailable) : ipAddress);
218        wifiIpAddressPref.setSelectable(false);
219    }
220
221    @Override
222    public int getMetricsCategory() {
223        return MetricsEvent.CONFIGURE_WIFI;
224    }
225
226    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
227        @Override
228        public void onReceive(Context context, Intent intent) {
229            String action = intent.getAction();
230            if (action.equals(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION) ||
231                action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
232                refreshWifiInfo();
233            }
234        }
235    };
236}
237