ConfigureWifiSettings.java revision 0b4fdc49fba83ad2a950681ef014b6927e438007
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.NetworkScoreManager;
23import android.net.NetworkScorerAppManager;
24import android.net.wifi.WifiConfiguration;
25import android.net.wifi.WifiInfo;
26import android.net.wifi.WifiManager;
27import android.os.Bundle;
28import android.os.UserManager;
29import android.provider.Settings;
30import android.support.v14.preference.SwitchPreference;
31import android.support.v7.preference.ListPreference;
32import android.support.v7.preference.Preference;
33import android.text.TextUtils;
34import android.util.Log;
35import android.widget.Toast;
36import com.android.settings.AppListSwitchPreference;
37import com.android.settings.InstrumentedFragment;
38import com.android.settings.R;
39import com.android.settings.SettingsPreferenceFragment;
40import com.android.settings.Utils;
41
42import java.util.Collection;
43import java.util.List;
44
45public class ConfigureWifiSettings extends SettingsPreferenceFragment
46        implements Preference.OnPreferenceChangeListener {
47    private static final String TAG = "ConfigureWifiSettings";
48
49    private static final String KEY_MAC_ADDRESS = "mac_address";
50    private static final String KEY_SAVED_NETWORKS = "saved_networks";
51    private static final String KEY_CURRENT_IP_ADDRESS = "current_ip_address";
52    private static final String KEY_FREQUENCY_BAND = "frequency_band";
53    private static final String KEY_NOTIFY_OPEN_NETWORKS = "notify_open_networks";
54    private static final String KEY_SLEEP_POLICY = "sleep_policy";
55    private static final String KEY_WIFI_ASSISTANT = "wifi_assistant";
56
57    private WifiManager mWifiManager;
58    private NetworkScoreManager mNetworkScoreManager;
59    private AppListSwitchPreference mWifiAssistantPreference;
60
61    private IntentFilter mFilter;
62
63    @Override
64    public void onCreate(Bundle icicle) {
65        super.onCreate(icicle);
66        addPreferencesFromResource(R.xml.wifi_configure_settings);
67    }
68
69    @Override
70    public void onActivityCreated(Bundle savedInstanceState) {
71        super.onActivityCreated(savedInstanceState);
72        mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
73        mFilter = new IntentFilter();
74        mFilter.addAction(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION);
75        mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
76        mNetworkScoreManager =
77                (NetworkScoreManager) getSystemService(Context.NETWORK_SCORE_SERVICE);
78    }
79
80    @Override
81    public void onResume() {
82        super.onResume();
83        initPreferences();
84        getActivity().registerReceiver(mReceiver, mFilter);
85        refreshWifiInfo();
86    }
87
88    @Override
89    public void onPause() {
90        super.onPause();
91        getActivity().unregisterReceiver(mReceiver);
92    }
93
94    private void initPreferences() {
95        List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks();
96        if (configs == null || configs.size() == 0) {
97            removePreference(KEY_SAVED_NETWORKS);
98        }
99
100        SwitchPreference notifyOpenNetworks =
101                (SwitchPreference) findPreference(KEY_NOTIFY_OPEN_NETWORKS);
102        notifyOpenNetworks.setChecked(Settings.Global.getInt(getContentResolver(),
103                Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0) == 1);
104        notifyOpenNetworks.setEnabled(mWifiManager.isWifiEnabled());
105
106        final Context context = getActivity();
107        mWifiAssistantPreference = (AppListSwitchPreference) findPreference(KEY_WIFI_ASSISTANT);
108        Collection<NetworkScorerAppManager.NetworkScorerAppData> scorers =
109                NetworkScorerAppManager.getAllValidScorers(context);
110        if (UserManager.get(context).isAdminUser() && !scorers.isEmpty()) {
111            mWifiAssistantPreference.setOnPreferenceChangeListener(this);
112            initWifiAssistantPreference(scorers);
113        } else if (mWifiAssistantPreference != null) {
114            getPreferenceScreen().removePreference(mWifiAssistantPreference);
115        }
116
117        ListPreference frequencyPref = (ListPreference) findPreference(KEY_FREQUENCY_BAND);
118
119        if (mWifiManager.isDualBandSupported()) {
120            frequencyPref.setOnPreferenceChangeListener(this);
121            int value = mWifiManager.getFrequencyBand();
122            if (value != -1) {
123                frequencyPref.setValue(String.valueOf(value));
124                updateFrequencyBandSummary(frequencyPref, value);
125            } else {
126                Log.e(TAG, "Failed to fetch frequency band");
127            }
128        } else {
129            if (frequencyPref != null) {
130                // null if it has already been removed before resume
131                getPreferenceScreen().removePreference(frequencyPref);
132            }
133        }
134
135        ListPreference sleepPolicyPref = (ListPreference) findPreference(KEY_SLEEP_POLICY);
136        if (sleepPolicyPref != null) {
137            if (Utils.isWifiOnly(context)) {
138                sleepPolicyPref.setEntries(R.array.wifi_sleep_policy_entries_wifi_only);
139            }
140            sleepPolicyPref.setOnPreferenceChangeListener(this);
141            int value = Settings.Global.getInt(getContentResolver(),
142                    Settings.Global.WIFI_SLEEP_POLICY,
143                    Settings.Global.WIFI_SLEEP_POLICY_NEVER);
144            String stringValue = String.valueOf(value);
145            sleepPolicyPref.setValue(stringValue);
146            updateSleepPolicySummary(sleepPolicyPref, stringValue);
147        }
148    }
149
150    private void updateSleepPolicySummary(Preference sleepPolicyPref, String value) {
151        if (value != null) {
152            String[] values = getResources().getStringArray(R.array.wifi_sleep_policy_values);
153            final int summaryArrayResId = Utils.isWifiOnly(getActivity()) ?
154                    R.array.wifi_sleep_policy_entries_wifi_only : R.array.wifi_sleep_policy_entries;
155            String[] summaries = getResources().getStringArray(summaryArrayResId);
156            for (int i = 0; i < values.length; i++) {
157                if (value.equals(values[i])) {
158                    if (i < summaries.length) {
159                        sleepPolicyPref.setSummary(summaries[i]);
160                        return;
161                    }
162                }
163            }
164        }
165
166        sleepPolicyPref.setSummary("");
167        Log.e(TAG, "Invalid sleep policy value: " + value);
168    }
169
170    @Override
171    public boolean onPreferenceTreeClick(Preference preference) {
172        String key = preference.getKey();
173
174        if (KEY_NOTIFY_OPEN_NETWORKS.equals(key)) {
175            Settings.Global.putInt(getContentResolver(),
176                    Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON,
177                    ((SwitchPreference) preference).isChecked() ? 1 : 0);
178        } else {
179            return super.onPreferenceTreeClick(preference);
180        }
181        return true;
182    }
183
184    @Override
185    public boolean onPreferenceChange(Preference preference, Object newValue) {
186        final Context context = getActivity();
187        String key = preference.getKey();
188
189        if (KEY_FREQUENCY_BAND.equals(key)) {
190            try {
191                int value = Integer.parseInt((String) newValue);
192                mWifiManager.setFrequencyBand(value, true);
193                updateFrequencyBandSummary(preference, value);
194            } catch (NumberFormatException e) {
195                Toast.makeText(context, R.string.wifi_setting_frequency_band_error,
196                        Toast.LENGTH_SHORT).show();
197                return false;
198            }
199        } else if (KEY_WIFI_ASSISTANT.equals(key)) {
200            NetworkScorerAppManager.NetworkScorerAppData wifiAssistant =
201                    NetworkScorerAppManager.getScorer(context, (String) newValue);
202            if (wifiAssistant == null) {
203                mNetworkScoreManager.setActiveScorer(null);
204                return true;
205            }
206
207            Intent intent = new Intent();
208            if (wifiAssistant.mConfigurationActivityClassName != null) {
209                // App has a custom configuration activity; launch that.
210                // This custom activity will be responsible for launching the system
211                // dialog.
212                intent.setClassName(wifiAssistant.mPackageName,
213                        wifiAssistant.mConfigurationActivityClassName);
214            } else {
215                // Fall back on the system dialog.
216                intent.setAction(NetworkScoreManager.ACTION_CHANGE_ACTIVE);
217                intent.putExtra(NetworkScoreManager.EXTRA_PACKAGE_NAME,
218                        wifiAssistant.mPackageName);
219            }
220
221            startActivity(intent);
222            // Don't update the preference widget state until the child activity returns.
223            // It will be updated in onResume after the activity finishes.
224            return false;
225        }
226
227        if (KEY_SLEEP_POLICY.equals(key)) {
228            try {
229                String stringValue = (String) newValue;
230                Settings.Global.putInt(getContentResolver(), Settings.Global.WIFI_SLEEP_POLICY,
231                        Integer.parseInt(stringValue));
232                updateSleepPolicySummary(preference, stringValue);
233            } catch (NumberFormatException e) {
234                Toast.makeText(context, R.string.wifi_setting_sleep_policy_error,
235                        Toast.LENGTH_SHORT).show();
236                return false;
237            }
238        }
239
240        return true;
241    }
242
243    private void refreshWifiInfo() {
244        final Context context = getActivity();
245        WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
246
247        Preference wifiMacAddressPref = findPreference(KEY_MAC_ADDRESS);
248        String macAddress = wifiInfo == null ? null : wifiInfo.getMacAddress();
249        wifiMacAddressPref.setSummary(!TextUtils.isEmpty(macAddress) ? macAddress
250                : context.getString(R.string.status_unavailable));
251        wifiMacAddressPref.setSelectable(false);
252
253        Preference wifiIpAddressPref = findPreference(KEY_CURRENT_IP_ADDRESS);
254        String ipAddress = Utils.getWifiIpAddresses(context);
255        wifiIpAddressPref.setSummary(ipAddress == null ?
256                context.getString(R.string.status_unavailable) : ipAddress);
257        wifiIpAddressPref.setSelectable(false);
258    }
259
260    private void updateFrequencyBandSummary(Preference frequencyBandPref, int index) {
261        String[] summaries = getResources().getStringArray(R.array.wifi_frequency_band_entries);
262        frequencyBandPref.setSummary(summaries[index]);
263    }
264
265    private void initWifiAssistantPreference(
266            Collection<NetworkScorerAppManager.NetworkScorerAppData> scorers) {
267        int count = scorers.size();
268        String[] packageNames = new String[count];
269        int i = 0;
270        for (NetworkScorerAppManager.NetworkScorerAppData scorer : scorers) {
271            packageNames[i] = scorer.mPackageName;
272            i++;
273        }
274        mWifiAssistantPreference.setPackageNames(packageNames,
275                mNetworkScoreManager.getActiveScorerPackage());
276    }
277
278    @Override
279    protected int getMetricsCategory() {
280        return InstrumentedFragment.CONFIGURE_WIFI;
281    }
282
283    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
284        @Override
285        public void onReceive(Context context, Intent intent) {
286            String action = intent.getAction();
287            if (action.equals(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION) ||
288                action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
289                refreshWifiInfo();
290            }
291        }
292    };
293}
294