summaryrefslogtreecommitdiff
path: root/src/com/android/networkrecommendation/notify/WifiNotificationController.java
blob: a7afcdd65232bb5e4f91703388c5e4fe0d68daa0 (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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
/*
 * 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.networkrecommendation.notify;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.graphics.Bitmap;
import android.net.NetworkInfo;
import android.net.NetworkScoreManager;
import android.net.RecommendationRequest;
import android.net.RecommendationResult;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;

import com.android.networkrecommendation.R;
import com.android.networkrecommendation.SynchronousNetworkRecommendationProvider;

import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Takes care of handling the "open wi-fi network available" notification
 * @hide
 */
public class WifiNotificationController {
    /**
     * The icon to show in the 'available networks' notification. This will also
     * be the ID of the Notification given to the NotificationManager.
     */
    private static final int ICON_NETWORKS_AVAILABLE = R.drawable.stat_notify_wifi_in_range;
    /**
     * When a notification is shown, we wait this amount before possibly showing it again.
     */
    private final long mNotificationRepeatDelayMs;
    /**
     * Whether the user has set the setting to show the 'available networks' notification.
     */
    private boolean mNotificationEnabled;
    /**
     * Observes the user setting to keep {@link #mNotificationEnabled} in sync.
     */
    private final NotificationEnabledSettingObserver mNotificationEnabledSettingObserver;
    /**
     * The {@link System#currentTimeMillis()} must be at least this value for us
     * to show the notification again.
     */
    private long mNotificationRepeatTime;
    /**
     * Whether the notification is being shown.
     */
    private boolean mNotificationShown;
    /**
     * The number of continuous scans that must occur before consider the
     * supplicant in a scanning state. This allows supplicant to associate with
     * remembered networks that are in the scan results.
     */
    private static final int NUM_SCANS_BEFORE_ACTUALLY_SCANNING = 3;
    /**
     * The number of scans since the last network state change. When this
     * exceeds {@link #NUM_SCANS_BEFORE_ACTUALLY_SCANNING}, we consider the
     * supplicant to actually be scanning. When the network state changes to
     * something other than scanning, we reset this to 0.
     */
    private int mNumScansSinceNetworkStateChange;
    /**
     * Time in milliseconds to display the Connecting notification.
     */
    private static final int TIME_TO_SHOW_CONNECTING_MILLIS = 10000;
    /**
     * Time in milliseconds to display the Connected notification.
     */
    private static final int TIME_TO_SHOW_CONNECTED_MILLIS = 5000;
    /**
     * Time in milliseconds to display the Failed To Connect notification.
     */
    private static final int TIME_TO_SHOW_FAILED_MILLIS = 5000;
    /**
     * Try to connect to provided WifiConfiguration since user wants to
     * connect to the recommended open access point.
     */
    static final String ACTION_CONNECT_TO_RECOMMENDED_NETWORK =
            "com.android.networkrecommendation.CONNECT_TO_RECOMMENDED_NETWORK";
    /**
     * Handles behavior when notification is deleted.
     */
    static final String ACTION_NOTIFICATION_DELETED =
            "com.android.networkrecommendation.NOTIFICATION_DELETED";
    /**
     * Network recommended by {@link NetworkScoreManager#requestRecommendation}.
     */
    private WifiConfiguration mRecommendedNetwork;
    private Bitmap mNotificationBadgeBitmap;
    /**
     * Whether {@link WifiNotificationController} has been started.
     */
    private final AtomicBoolean mStarted;
    /**
     * Runnable to dismiss notification.
     */
    @VisibleForTesting
    final Runnable mDismissNotificationRunnable = () -> {
        removeNotification();
    };
    /**
     * Runnable to show Failed To Connect notification.
     */
    @VisibleForTesting
    final Runnable mShowFailedToConnectNotificationRunnable = () -> {
        showFailedToConnectNotification();
    };

    private static final String TAG = "WifiNotification";

    private final Context mContext;
    private final Handler mHandler;
    private final ContentResolver mContentResolver;
    private final SynchronousNetworkRecommendationProvider mNetworkRecommendationProvider;
    private final WifiManager mWifiManager;
    private final NotificationManager mNotificationManager;
    private final WifiNotificationHelper mWifiNotificationHelper;
    private NetworkInfo mNetworkInfo;
    private NetworkInfo.DetailedState mDetailedState;
    private volatile int mWifiState;

    public WifiNotificationController(Context context, ContentResolver contentResolver,
            Handler handler,
            SynchronousNetworkRecommendationProvider networkRecommendationProvider,
            WifiManager wifiManager, NotificationManager notificationManager,
            WifiNotificationHelper helper) {
        mContext = context;
        mContentResolver = contentResolver;
        mNetworkRecommendationProvider = networkRecommendationProvider;
        mWifiManager = wifiManager;
        mNotificationManager = notificationManager;
        mHandler = handler;
        mWifiNotificationHelper = helper;
        mStarted = new AtomicBoolean(false);

        // Setting is in seconds
        mNotificationRepeatDelayMs = Settings.Global.getInt(
                contentResolver, Settings.Global.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000L;
        mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(mHandler);
    }

    /** Starts {@link WifiNotificationController}. */
    public void start() {
        if (!mStarted.compareAndSet(false, true)) {
            return;
        }

        mWifiState = WifiManager.WIFI_STATE_UNKNOWN;
        mDetailedState = NetworkInfo.DetailedState.IDLE;

        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        filter.addAction(ACTION_CONNECT_TO_RECOMMENDED_NETWORK);
        filter.addAction(ACTION_NOTIFICATION_DELETED);

        mContext.registerReceiver(
                mBroadcastReceiver, filter, null /* broadcastPermission */, mHandler);
        mNotificationEnabledSettingObserver.register();
    }

    /** Stops {@link WifiNotificationController}. */
    public void stop() {
        if (!mStarted.compareAndSet(true, false)) {
            return;
        }
        mContext.unregisterReceiver(mBroadcastReceiver);
        mNotificationEnabledSettingObserver.register();
    }

    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                mWifiState = mWifiManager.getWifiState();
                resetNotification();
            } else if (intent.getAction().equals(
                    WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                mNetworkInfo = (NetworkInfo) intent.getParcelableExtra(
                        WifiManager.EXTRA_NETWORK_INFO);
                NetworkInfo.DetailedState detailedState =
                        mNetworkInfo.getDetailedState();
                if (detailedState != NetworkInfo.DetailedState.SCANNING
                        && detailedState != mDetailedState) {
                    mDetailedState = detailedState;
                    switch (mDetailedState) {
                        case CONNECTED:
                            updateNotificationOnConnect();
                            break;
                        case DISCONNECTED:
                        case CAPTIVE_PORTAL_CHECK:
                            resetNotification();
                            break;

                        // TODO: figure out if these are failure cases when connecting
                        case IDLE:
                        case SCANNING:
                        case CONNECTING:
                        case AUTHENTICATING:
                        case OBTAINING_IPADDR:
                        case SUSPENDED:
                        case FAILED:
                        case BLOCKED:
                        case VERIFYING_POOR_LINK:
                            break;
                    }
                }
            } else if (intent.getAction().equals(
                    WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                checkAndSetNotification(mNetworkInfo, mWifiManager.getScanResults());
            } else if (intent.getAction().equals(ACTION_CONNECT_TO_RECOMMENDED_NETWORK)) {
                connectToRecommendedNetwork();
            } else if (intent.getAction().equals(ACTION_NOTIFICATION_DELETED)) {
                handleNotificationDeleted();
            }
        }
    };

    private void checkAndSetNotification(NetworkInfo networkInfo,
            List<ScanResult> scanResults) {

        // TODO: unregister broadcast so we do not have to check here
        // If we shouldn't place a notification on available networks, then
        // don't bother doing any of the following
        if (!mNotificationEnabled) return;
        if (mWifiState != WifiManager.WIFI_STATE_ENABLED) return;
        if (scanResults == null || scanResults.isEmpty()) return;

        NetworkInfo.State state = NetworkInfo.State.DISCONNECTED;
        if (networkInfo != null) {
            state = networkInfo.getState();
        }


        if (state == NetworkInfo.State.DISCONNECTED
                || state == NetworkInfo.State.UNKNOWN) {
            RecommendationResult result = getOpenNetworkRecommendation(scanResults);
            if (result != null
                    && result.getWifiConfiguration() != null) {
                mRecommendedNetwork = result.getWifiConfiguration();
                mNotificationBadgeBitmap = mWifiNotificationHelper.createNotificationBadgeBitmap(
                        mRecommendedNetwork, scanResults);
                if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING
                        && mNotificationBadgeBitmap != null) {
                    /*
                     * We have scanned continuously at least
                     * NUM_SCANS_BEFORE_NOTIFICATION times. The user
                     * probably does not have a remembered network in range,
                     * since otherwise supplicant would have tried to
                     * associate and thus resetting this counter.
                     */
                    displayNotification();
                }
                return;
            }
        }

        // No open networks in range, remove the notification
        removeNotification();
    }

    /**
     * Uses {@link NetworkScoreManager} to choose a qualified network out of the list of
     * {@link ScanResult}s.
     *
     * @return returns the best qualified open networks, if any.
     */
    @Nullable
    private RecommendationResult getOpenNetworkRecommendation(List<ScanResult> scanResults) {
        if (scanResults == null || scanResults.isEmpty()) {
            return null;
        }
        ArrayList<ScanResult> openNetworks = new ArrayList<>();
        for (ScanResult scanResult : scanResults) {
            //A capability of [ESS] represents an open access point
            //that is available for an STA to connect
            if ("[ESS]".equals(scanResult.capabilities)) {
                openNetworks.add(scanResult);
            }
        }
        RecommendationRequest request = new RecommendationRequest.Builder()
                .setScanResults(openNetworks.toArray(new ScanResult[openNetworks.size()]))
                .build();

        return mNetworkRecommendationProvider.requestRecommendation(request);
    }

    /**
     * Display's a notification that there are open Wi-Fi networks.
     */
    private void displayNotification() {

        // Since we use auto cancel on the notification, when the
        // mNetworksAvailableNotificationShown is true, the notification may
        // have actually been canceled.  However, when it is false we know
        // for sure that it is not being shown (it will not be shown any other
        // place than here)

        // Not enough time has passed to show the notification again

        if (System.currentTimeMillis() < mNotificationRepeatTime) {
            return;
        }
        Notification notification = mWifiNotificationHelper.createMainNotification(
                        mRecommendedNetwork, mNotificationBadgeBitmap);
        mNotificationRepeatTime = System.currentTimeMillis() + mNotificationRepeatDelayMs;

        postNotification(notification);
        mNotificationShown = true;
    }


    /**
     * Attempts to connect to recommended network and updates the notification to
     * show Connecting state.
     * TODO(33668991): work with UX to polish notification UI and figure out failure states
     */
    private void connectToRecommendedNetwork() {
        if (mRecommendedNetwork == null) {
            return;
        }
        // Attempts to connect to recommended network.
        mWifiManager.connect(mRecommendedNetwork, null /* actionListener */);

        // Update notification to connecting status.
        Notification notification = mWifiNotificationHelper.createConnectingNotification(
                        mRecommendedNetwork, mNotificationBadgeBitmap);
        postNotification(notification);
        mHandler.postDelayed(mShowFailedToConnectNotificationRunnable,
                TIME_TO_SHOW_CONNECTING_MILLIS);
    }

    /**
     * When detailed state changes to CONNECTED, show connected notification or
     * reset notification.
     * TODO: determine failure state where main notification shows but connected.
     */
    private void updateNotificationOnConnect() {
        if (!mNotificationShown) {
            return;
        }

        Notification notification = mWifiNotificationHelper.createConnectedNotification(
                mRecommendedNetwork, mNotificationBadgeBitmap);
        postNotification(notification);
        // Remove any previous reset notification callbacks.
        mHandler.removeCallbacks(mShowFailedToConnectNotificationRunnable);
        mHandler.postDelayed(mDismissNotificationRunnable, TIME_TO_SHOW_CONNECTED_MILLIS);
    }

    /**
     * Displays the Failed To Connect notification after the Connecting notification
     * is shown for {@link #TIME_TO_SHOW_CONNECTING_MILLIS} duration.
     */
    private void showFailedToConnectNotification() {
        Notification notification =
                mWifiNotificationHelper.createFailedToConnectNotification(mRecommendedNetwork);
        postNotification(notification);
        mHandler.postDelayed(mDismissNotificationRunnable, TIME_TO_SHOW_FAILED_MILLIS);
    }

    /**
     * Handles behavior when notification is dismissed.
     */
    private void handleNotificationDeleted() {
        mNotificationShown = false;
        mRecommendedNetwork = null;
        mNotificationBadgeBitmap = null;
    }

    private void postNotification(Notification notification) {
        mNotificationManager.notify(null /* tag */, ICON_NETWORKS_AVAILABLE, notification);
    }

    /**
     * Clears variables related to tracking whether a notification has been
     * shown recently and clears the current notification.
     */
    private void resetNotification() {
        mNotificationRepeatTime = 0;
        mNumScansSinceNetworkStateChange = 0;
        if (mNotificationShown) {
            removeNotification();
        }
    }

    private void removeNotification() {
        mNotificationManager.cancel(null /* tag */, ICON_NETWORKS_AVAILABLE);
        mNotificationShown = false;
    }

    /** Dump debugging information. */
    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
        pw.println("mNotificationEnabled " + mNotificationEnabled);
        pw.println("mNotificationRepeatTime " + mNotificationRepeatTime);
        pw.println("mNotificationShown " + mNotificationShown);
        pw.println("mNumScansSinceNetworkStateChange " + mNumScansSinceNetworkStateChange);
    }

    private class NotificationEnabledSettingObserver extends ContentObserver {
        NotificationEnabledSettingObserver(Handler handler) {
            super(handler);
        }

        public void register() {
            mContentResolver.registerContentObserver(Settings.Global.getUriFor(
                    Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this);
            mNotificationEnabled = getValue();
        }

        public void unregister() {
            mContentResolver.unregisterContentObserver(this);
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);

            mNotificationEnabled = getValue();
            resetNotification();
        }

        private boolean getValue() {
            return Settings.Global.getInt(
                    mContentResolver,
                    Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0) == 1;
        }
    }
}