1/*
2 * Copyright (C) 2013 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 */
16
17package com.android.server.wifi;
18
19import android.app.Notification;
20import android.app.NotificationManager;
21import android.app.TaskStackBuilder;
22import android.content.BroadcastReceiver;
23import android.content.ContentResolver;
24import android.content.Context;
25import android.content.Intent;
26import android.content.IntentFilter;
27import android.database.ContentObserver;
28import android.net.NetworkInfo;
29import android.net.wifi.ScanResult;
30import android.net.wifi.WifiManager;
31import android.net.wifi.WifiStateMachine;
32import android.os.Handler;
33import android.os.Message;
34import android.os.UserHandle;
35import android.provider.Settings;
36
37import java.io.FileDescriptor;
38import java.io.PrintWriter;
39import java.util.List;
40
41/* Takes care of handling the "open wi-fi network available" notification @hide */
42final class WifiNotificationController {
43    /**
44     * The icon to show in the 'available networks' notification. This will also
45     * be the ID of the Notification given to the NotificationManager.
46     */
47    private static final int ICON_NETWORKS_AVAILABLE =
48            com.android.internal.R.drawable.stat_notify_wifi_in_range;
49    /**
50     * When a notification is shown, we wait this amount before possibly showing it again.
51     */
52    private final long NOTIFICATION_REPEAT_DELAY_MS;
53    /**
54     * Whether the user has set the setting to show the 'available networks' notification.
55     */
56    private boolean mNotificationEnabled;
57    /**
58     * Observes the user setting to keep {@link #mNotificationEnabled} in sync.
59     */
60    private NotificationEnabledSettingObserver mNotificationEnabledSettingObserver;
61    /**
62     * The {@link System#currentTimeMillis()} must be at least this value for us
63     * to show the notification again.
64     */
65    private long mNotificationRepeatTime;
66    /**
67     * The Notification object given to the NotificationManager.
68     */
69    private Notification mNotification;
70    /**
71     * Whether the notification is being shown, as set by us. That is, if the
72     * user cancels the notification, we will not receive the callback so this
73     * will still be true. We only guarantee if this is false, then the
74     * notification is not showing.
75     */
76    private boolean mNotificationShown;
77    /**
78     * The number of continuous scans that must occur before consider the
79     * supplicant in a scanning state. This allows supplicant to associate with
80     * remembered networks that are in the scan results.
81     */
82    private static final int NUM_SCANS_BEFORE_ACTUALLY_SCANNING = 3;
83    /**
84     * The number of scans since the last network state change. When this
85     * exceeds {@link #NUM_SCANS_BEFORE_ACTUALLY_SCANNING}, we consider the
86     * supplicant to actually be scanning. When the network state changes to
87     * something other than scanning, we reset this to 0.
88     */
89    private int mNumScansSinceNetworkStateChange;
90
91    private final Context mContext;
92    private final WifiStateMachine mWifiStateMachine;
93    private NetworkInfo mNetworkInfo;
94    private volatile int mWifiState;
95
96    WifiNotificationController(Context context, WifiStateMachine wsm) {
97        mContext = context;
98        mWifiStateMachine = wsm;
99        mWifiState = WifiManager.WIFI_STATE_UNKNOWN;
100
101        IntentFilter filter = new IntentFilter();
102        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
103        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
104        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
105
106        mContext.registerReceiver(
107                new BroadcastReceiver() {
108                    @Override
109                    public void onReceive(Context context, Intent intent) {
110                        if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
111                            mWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
112                                    WifiManager.WIFI_STATE_UNKNOWN);
113                            resetNotification();
114                        } else if (intent.getAction().equals(
115                                WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
116                            mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
117                                    WifiManager.EXTRA_NETWORK_INFO);
118                            // reset & clear notification on a network connect & disconnect
119                            switch(mNetworkInfo.getDetailedState()) {
120                                case CONNECTED:
121                                case DISCONNECTED:
122                                case CAPTIVE_PORTAL_CHECK:
123                                    resetNotification();
124                                    break;
125                            }
126                        } else if (intent.getAction().equals(
127                                WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
128                            checkAndSetNotification(mNetworkInfo,
129                                    mWifiStateMachine.syncGetScanResultsList());
130                        }
131                    }
132                }, filter);
133
134        // Setting is in seconds
135        NOTIFICATION_REPEAT_DELAY_MS = Settings.Global.getInt(context.getContentResolver(),
136                Settings.Global.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000l;
137        mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(new Handler());
138        mNotificationEnabledSettingObserver.register();
139    }
140
141    private synchronized void checkAndSetNotification(NetworkInfo networkInfo,
142            List<ScanResult> scanResults) {
143        // TODO: unregister broadcast so we do not have to check here
144        // If we shouldn't place a notification on available networks, then
145        // don't bother doing any of the following
146        if (!mNotificationEnabled) return;
147        if (networkInfo == null) return;
148        if (mWifiState != WifiManager.WIFI_STATE_ENABLED) return;
149
150        NetworkInfo.State state = networkInfo.getState();
151        if ((state == NetworkInfo.State.DISCONNECTED)
152                || (state == NetworkInfo.State.UNKNOWN)) {
153            if (scanResults != null) {
154                int numOpenNetworks = 0;
155                for (int i = scanResults.size() - 1; i >= 0; i--) {
156                    ScanResult scanResult = scanResults.get(i);
157
158                    //A capability of [ESS] represents an open access point
159                    //that is available for an STA to connect
160                    if (scanResult.capabilities != null &&
161                            scanResult.capabilities.equals("[ESS]")) {
162                        numOpenNetworks++;
163                    }
164                }
165
166                if (numOpenNetworks > 0) {
167                    if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
168                        /*
169                         * We've scanned continuously at least
170                         * NUM_SCANS_BEFORE_NOTIFICATION times. The user
171                         * probably does not have a remembered network in range,
172                         * since otherwise supplicant would have tried to
173                         * associate and thus resetting this counter.
174                         */
175                        setNotificationVisible(true, numOpenNetworks, false, 0);
176                    }
177                    return;
178                }
179            }
180        }
181
182        // No open networks in range, remove the notification
183        setNotificationVisible(false, 0, false, 0);
184    }
185
186    /**
187     * Clears variables related to tracking whether a notification has been
188     * shown recently and clears the current notification.
189     */
190    private synchronized void resetNotification() {
191        mNotificationRepeatTime = 0;
192        mNumScansSinceNetworkStateChange = 0;
193        setNotificationVisible(false, 0, false, 0);
194    }
195
196    /**
197     * Display or don't display a notification that there are open Wi-Fi networks.
198     * @param visible {@code true} if notification should be visible, {@code false} otherwise
199     * @param numNetworks the number networks seen
200     * @param force {@code true} to force notification to be shown/not-shown,
201     * even if it is already shown/not-shown.
202     * @param delay time in milliseconds after which the notification should be made
203     * visible or invisible.
204     */
205    private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
206            int delay) {
207
208        // Since we use auto cancel on the notification, when the
209        // mNetworksAvailableNotificationShown is true, the notification may
210        // have actually been canceled.  However, when it is false we know
211        // for sure that it is not being shown (it will not be shown any other
212        // place than here)
213
214        // If it should be hidden and it is already hidden, then noop
215        if (!visible && !mNotificationShown && !force) {
216            return;
217        }
218
219        NotificationManager notificationManager = (NotificationManager) mContext
220                .getSystemService(Context.NOTIFICATION_SERVICE);
221
222        Message message;
223        if (visible) {
224
225            // Not enough time has passed to show the notification again
226            if (System.currentTimeMillis() < mNotificationRepeatTime) {
227                return;
228            }
229
230            if (mNotification == null) {
231                // Cache the Notification object.
232                mNotification = new Notification();
233                mNotification.when = 0;
234                mNotification.icon = ICON_NETWORKS_AVAILABLE;
235                mNotification.flags = Notification.FLAG_AUTO_CANCEL;
236                mNotification.contentIntent = TaskStackBuilder.create(mContext)
237                        .addNextIntentWithParentStack(
238                                new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK))
239                        .getPendingIntent(0, 0, null, UserHandle.CURRENT);
240            }
241
242            CharSequence title = mContext.getResources().getQuantityText(
243                    com.android.internal.R.plurals.wifi_available, numNetworks);
244            CharSequence details = mContext.getResources().getQuantityText(
245                    com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
246            mNotification.tickerText = title;
247            mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
248
249            mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
250
251            notificationManager.notifyAsUser(null, ICON_NETWORKS_AVAILABLE, mNotification,
252                    UserHandle.ALL);
253        } else {
254            notificationManager.cancelAsUser(null, ICON_NETWORKS_AVAILABLE, UserHandle.ALL);
255        }
256
257        mNotificationShown = visible;
258    }
259
260    void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
261        pw.println("mNotificationEnabled " + mNotificationEnabled);
262        pw.println("mNotificationRepeatTime " + mNotificationRepeatTime);
263        pw.println("mNotificationShown " + mNotificationShown);
264        pw.println("mNumScansSinceNetworkStateChange " + mNumScansSinceNetworkStateChange);
265    }
266
267    private class NotificationEnabledSettingObserver extends ContentObserver {
268        public NotificationEnabledSettingObserver(Handler handler) {
269            super(handler);
270        }
271
272        public void register() {
273            ContentResolver cr = mContext.getContentResolver();
274            cr.registerContentObserver(Settings.Global.getUriFor(
275                    Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
276            synchronized (WifiNotificationController.this) {
277                mNotificationEnabled = getValue();
278            }
279        }
280
281        @Override
282        public void onChange(boolean selfChange) {
283            super.onChange(selfChange);
284
285            synchronized (WifiNotificationController.this) {
286                mNotificationEnabled = getValue();
287                resetNotification();
288            }
289        }
290
291        private boolean getValue() {
292            return Settings.Global.getInt(mContext.getContentResolver(),
293                    Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
294        }
295    }
296
297}
298