summaryrefslogtreecommitdiffstats
path: root/src/com/android/settings/wifi/SavedAccessPointsWifiSettings.java
blob: e7166daa2f926d6bc47f0b5e59b2129aa762688e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/*
 * Copyright (C) 2014 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 static android.os.UserManager.DISALLOW_CONFIG_WIFI;

import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.preference.Preference;
import android.preference.PreferenceScreen;
import android.util.Log;

import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.android.internal.logging.MetricsLogger;
import com.android.settings.DraggableSortListView;
import com.android.settings.R;
import com.android.settings.RestrictedSettingsFragment;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.search.BaseSearchIndexProvider;
import com.android.settings.search.Indexable;
import com.android.settings.search.SearchIndexableRaw;
import com.android.settings.wifi.AccessPointPreference.UserBadgeCache;
import com.android.settingslib.wifi.AccessPoint;
import com.android.settingslib.wifi.WifiTracker;
import cyanogenmod.providers.CMSettings;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * UI to manage saved networks/access points.
 */
public class SavedAccessPointsWifiSettings extends RestrictedSettingsFragment
        implements DialogInterface.OnClickListener, Indexable {
    private static final String TAG = "SavedAccessPointsWifiSettings";

    private DraggableSortListView.DropListener mDropListener =
            new DraggableSortListView.DropListener() {
                @Override
                public void drop(int from, int to) {
                    if (from == to) return;

                    PreferenceScreen preferences = getPreferenceScreen();
                    int count = preferences.getPreferenceCount();

                    // Sort the new list
                    List<AccessPointPreference> aps = new ArrayList<>(count);
                    for (int i = 0; i < count; i++) {
                        aps.add((AccessPointPreference) preferences.getPreference(i));
                    }
                    AccessPointPreference o = aps.remove(from);
                    aps.add(to, o);

                    // Update the priorities
                    for (int i = 0; i < count; i++) {
                        AccessPoint ap = aps.get(i).getAccessPoint();
                        WifiConfiguration config = ap.getConfig();
                        config.priority = count - i;

                        mWifiManager.updateNetwork(config);
                    }

                    // Now, save all the Wi-Fi configuration with its new priorities
                    mWifiManager.saveConfiguration();
                    mPrioritiesOrderChanged = true;

                    // Redraw the listview
                    initPreferences();
                }
            };

    private final ContentObserver mSettingsObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange, Uri uri) {
            mNetworksListView.setDropListener(isAutoConfigPriorities() ? null : mDropListener);
            getActivity().invalidateOptionsMenu();
        }
    };


    private static final int MENU_ID_AUTO_CONFIG_PRIORITIES = Menu.FIRST;

    private WifiDialog mDialog;
    private WifiManager mWifiManager;
    private AccessPoint mDlgAccessPoint;
    private Bundle mAccessPointSavedState;
    private AccessPoint mSelectedAccessPoint;
    private boolean mPrioritiesOrderChanged;

    private UserBadgeCache mUserBadgeCache;

    private DraggableSortListView mNetworksListView;

    // Instance state key
    private static final String SAVE_DIALOG_ACCESS_POINT_STATE = "wifi_ap_state";
    private static final String PRIORITIES_ORDER_CHANGED_STATE = "priorities_order_changed";

    public SavedAccessPointsWifiSettings() {
        super(DISALLOW_CONFIG_WIFI);
    }

    @Override
    protected int getMetricsCategory() {
        return MetricsLogger.WIFI_SAVED_ACCESS_POINTS;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.wifi_display_saved_access_points);
        mUserBadgeCache = new UserBadgeCache(getPackageManager());
    }

    @Override
    public void onResume() {
        super.onResume();
        initPreferences();

        mNetworksListView.setDropListener(isAutoConfigPriorities() ? null : mDropListener);
        getActivity().invalidateOptionsMenu();
        ContentResolver resolver = getContentResolver();
        resolver.registerContentObserver(CMSettings.Global.getUriFor(
                CMSettings.Global.WIFI_AUTO_PRIORITIES_CONFIGURATION), false, mSettingsObserver);
    }

    @Override
    public void onPause() {
        super.onResume();
        getContentResolver().unregisterContentObserver(mSettingsObserver);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mNetworksListView = new DraggableSortListView(getActivity());
        mNetworksListView.setId(android.R.id.list);
        mNetworksListView.setDropListener(mDropListener);
        return mNetworksListView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

        if (savedInstanceState != null) {
            if (savedInstanceState.containsKey(SAVE_DIALOG_ACCESS_POINT_STATE)) {
                mAccessPointSavedState =
                    savedInstanceState.getBundle(SAVE_DIALOG_ACCESS_POINT_STATE);
                mDlgAccessPoint = new AccessPoint(getActivity(), mAccessPointSavedState);
                mSelectedAccessPoint = mDlgAccessPoint;
            }
            mPrioritiesOrderChanged = savedInstanceState.getBoolean(
                    PRIORITIES_ORDER_CHANGED_STATE, false);
        }

        registerForContextMenu(getListView());
        setHasOptionsMenu(true);
    }

    @Override
    public void onDetach() {
        super.onDetach();

        if (mPrioritiesOrderChanged) {
            // Send a disconnect to ensure the new wifi priorities are detected
            mWifiManager.disconnect();
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // If the user is not allowed to configure wifi, do not show the menu.
        if (isUiRestricted()) return;

        addOptionsMenuItems(menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    void addOptionsMenuItems(Menu menu) {
        menu.add(Menu.NONE, MENU_ID_AUTO_CONFIG_PRIORITIES, 0, R.string.wifi_auto_config_priorities)
                .setCheckable(true)
                .setChecked(isAutoConfigPriorities())
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // If the user is not allowed to configure wifi, do not handle menu selections.
        if (isUiRestricted()) return false;

        switch (item.getItemId()) {
            case MENU_ID_AUTO_CONFIG_PRIORITIES:
                boolean autoConfig = !item.isChecked();

                // Set the system settings and refresh the listview
                CMSettings.Global.putInt(getActivity().getContentResolver(),
                        CMSettings.Global.WIFI_AUTO_PRIORITIES_CONFIGURATION, autoConfig ? 1 : 0);
                mNetworksListView.setDropListener(autoConfig ? null : mDropListener);
                item.setChecked(autoConfig);

                if (!autoConfig) {
                    // Reenable all the entries
                    PreferenceScreen preferences = getPreferenceScreen();
                    int count = preferences.getPreferenceCount();
                    for (int i = 0; i < count; i++) {
                        AccessPoint ap = ((AccessPointPreference)
                                preferences.getPreference(i)).getAccessPoint();
                        WifiConfiguration config = ap.getConfig();
                        mWifiManager.enableNetwork(config.networkId, false);
                    }
                }
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initPreferences() {
        PreferenceScreen preferenceScreen = getPreferenceScreen();
        final Context context = getActivity();

        final List<AccessPoint> accessPoints = WifiTracker.getCurrentAccessPoints(context, true,
                false, true);
        // Sort network list by priority (or by network id if the priority is the same)
        Collections.sort(accessPoints, new Comparator<AccessPoint>() {
            @Override
            public int compare(AccessPoint lhs, AccessPoint rhs) {
                WifiConfiguration lwc = lhs.getConfig();
                WifiConfiguration rwc = rhs.getConfig();

                // > priority -- > lower position
                if (lwc.priority < rwc.priority) return 1;
                if (lwc.priority > rwc.priority) return -1;
                // < network id -- > lower position
                if (lhs.getNetworkId() < rhs.getNetworkId()) return -1;
                if (lhs.getNetworkId() > rhs.getNetworkId()) return 1;
                return 0;
            }
        });
        preferenceScreen.setOrderingAsAdded(false);
        preferenceScreen.removeAll();

        final int accessPointsSize = accessPoints.size();
        for (int i = 0; i < accessPointsSize; ++i){
            AccessPoint accessPoint = accessPoints.get(i);
            AccessPointPreference preference = new AccessPointPreference(accessPoint,
                    context, mUserBadgeCache, true, true);
            if (mSelectedAccessPoint != null &&
                    mSelectedAccessPoint.getNetworkId() == accessPoint.getNetworkId()) {
                mSelectedAccessPoint = accessPoint;
            }
            preference.setOrder(i);
            preferenceScreen.addPreference(preference);
        }

        if (getPreferenceScreen().getPreferenceCount() < 1) {
            Log.w(TAG, "Saved networks activity loaded, but there are no saved networks!");
        }
    }

    private void showDialog(AccessPointPreference accessPoint, boolean edit) {
        if (mDialog != null) {
            removeDialog(WifiSettings.WIFI_DIALOG_ID);
            mDialog = null;
        }

        // Save the access point and edit mode
        mDlgAccessPoint = accessPoint.getAccessPoint();

        showDialog(WifiSettings.WIFI_DIALOG_ID);
    }

    @Override
    public Dialog onCreateDialog(int dialogId) {
        switch (dialogId) {
            case WifiSettings.WIFI_DIALOG_ID:
                mSelectedAccessPoint = mDlgAccessPoint;

                // Hide forget button if config editing is locked down
                final boolean hideForgetButton = WifiSettings.isEditabilityLockedDown(getActivity(),
                        mDlgAccessPoint.getConfig());
                mDialog = new WifiDialog(getActivity(), this, mDlgAccessPoint,
                        false /* not editting */, false, true /* hide the submit button */,
                        hideForgetButton);
                return mDialog;

        }
        return super.onCreateDialog(dialogId);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // If the dialog is showing, save its state.
        if (mDialog != null && mDialog.isShowing()) {
            if (mDlgAccessPoint != null) {
                mAccessPointSavedState = new Bundle();
                mDlgAccessPoint.saveWifiState(mAccessPointSavedState);
                outState.putBundle(SAVE_DIALOG_ACCESS_POINT_STATE, mAccessPointSavedState);
            }
        }
        outState.putBoolean(PRIORITIES_ORDER_CHANGED_STATE, mPrioritiesOrderChanged);
    }

    @Override
    public void onClick(DialogInterface dialogInterface, int button) {
        if (button == WifiDialog.BUTTON_FORGET && mSelectedAccessPoint != null) {
            mWifiManager.forget(mSelectedAccessPoint.getConfig().networkId, null);
            getPreferenceScreen().removePreference((Preference) mSelectedAccessPoint.getTag());
            mSelectedAccessPoint = null;
        }
    }

    @Override
    public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) {
        if (preference instanceof AccessPointPreference) {
            showDialog((AccessPointPreference) preference, false);
            return true;
        } else{
            return super.onPreferenceTreeClick(screen, preference);
        }
    }

    private boolean isAutoConfigPriorities() {
        return CMSettings.Global.getInt(getActivity().getContentResolver(),
                CMSettings.Global.WIFI_AUTO_PRIORITIES_CONFIGURATION, 1) != 0;
    }

    /**
     * For search.
     */
    public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
        new BaseSearchIndexProvider() {
            @Override
            public List<SearchIndexableRaw> getRawDataToIndex(Context context, boolean enabled) {
                final List<SearchIndexableRaw> result = new ArrayList<SearchIndexableRaw>();
                final Resources res = context.getResources();
                final String title = res.getString(R.string.wifi_saved_access_points_titlebar);

                // Add fragment title
                SearchIndexableRaw data = new SearchIndexableRaw(context);
                data.title = title;
                data.screenTitle = title;
                data.enabled = enabled;
                result.add(data);

                // Add available Wi-Fi access points
                final List<AccessPoint> accessPoints = WifiTracker.getCurrentAccessPoints(context,
                        true, false, true);

                final int accessPointsSize = accessPoints.size();
                for (int i = 0; i < accessPointsSize; ++i){
                    data = new SearchIndexableRaw(context);
                    data.title = accessPoints.get(i).getSsidStr();
                    data.screenTitle = title;
                    data.enabled = enabled;
                    result.add(data);
                }

                return result;
            }
        };
}