ONA: Refactor notification builder and register broadcast receiver.

Refactors the posting of the ONA notification by using a notification
builder from the framework facade. The notification building is isolated
in a helper class. OpenNetworkNotifier registers a broadcast receiver to
listen to user actions like swiping to dismiss and notification content
clicks. Also plumbs in a clock to stop using System#currentTimeMillis.

Bug: 38460614
Bug: 37357441
Bug: 62410249
Bug: 63544378
Test: frameworks/opt/net/wifi/tests/wifitests/runtests.sh

Change-Id: Ifa1eef1f17c3f3271ec4a11f4311ea00a2698be3
diff --git a/service/java/com/android/server/wifi/OpenNetworkNotificationBuilder.java b/service/java/com/android/server/wifi/OpenNetworkNotificationBuilder.java
new file mode 100644
index 0000000..5963b57
--- /dev/null
+++ b/service/java/com/android/server/wifi/OpenNetworkNotificationBuilder.java
@@ -0,0 +1,91 @@
+/*
+ * 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.server.wifi;
+
+import static com.android.server.wifi.OpenNetworkNotifier.ACTION_USER_DISMISSED_NOTIFICATION;
+import static com.android.server.wifi.OpenNetworkNotifier.ACTION_USER_TAPPED_CONTENT;
+
+import android.app.Notification;
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+import android.content.res.Resources;
+
+import com.android.internal.R;
+import com.android.internal.notification.SystemNotificationChannels;
+
+/**
+ * Helper to create notifications for {@link OpenNetworkNotifier}.
+ */
+public class OpenNetworkNotificationBuilder {
+
+    private Context mContext;
+    private Resources mResources;
+    private FrameworkFacade mFrameworkFacade;
+
+    public OpenNetworkNotificationBuilder(
+            Context context,
+            FrameworkFacade framework) {
+        mContext = context;
+        mResources = context.getResources();
+        mFrameworkFacade = framework;
+    }
+
+    /**
+     * Creates the open network available notification that alerts users there are open networks
+     * nearby.
+     */
+    public Notification createOpenNetworkAvailableNotification(int numNetworks) {
+
+        CharSequence title = mResources.getQuantityText(
+                com.android.internal.R.plurals.wifi_available, numNetworks);
+        CharSequence content = mResources.getQuantityText(
+                com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
+
+        PendingIntent contentIntent =
+                mFrameworkFacade.getBroadcast(
+                        mContext,
+                        0,
+                        new Intent(ACTION_USER_TAPPED_CONTENT),
+                        PendingIntent.FLAG_UPDATE_CURRENT);
+        return createNotificationBuilder(title, content)
+                .setContentIntent(contentIntent)
+                .build();
+    }
+
+    private Notification.Builder createNotificationBuilder(
+            CharSequence title, CharSequence content) {
+        PendingIntent deleteIntent =
+                mFrameworkFacade.getBroadcast(
+                        mContext,
+                        0,
+                        new Intent(ACTION_USER_DISMISSED_NOTIFICATION),
+                        PendingIntent.FLAG_UPDATE_CURRENT);
+        return mFrameworkFacade.makeNotificationBuilder(mContext,
+                SystemNotificationChannels.NETWORK_AVAILABLE)
+                .setSmallIcon(R.drawable.stat_notify_wifi_in_range)
+                .setAutoCancel(true)
+                .setTicker(title)
+                .setContentTitle(title)
+                .setContentText(content)
+                .setDeleteIntent(deleteIntent)
+                .setShowWhen(false)
+                .setLocalOnly(true)
+                .setColor(mResources.getColor(R.color.system_notification_accent_color,
+                        mContext.getTheme()));
+    }
+}
diff --git a/service/java/com/android/server/wifi/OpenNetworkNotifier.java b/service/java/com/android/server/wifi/OpenNetworkNotifier.java
index dee6c2f..fc144c1 100644
--- a/service/java/com/android/server/wifi/OpenNetworkNotifier.java
+++ b/service/java/com/android/server/wifi/OpenNetworkNotifier.java
@@ -17,22 +17,21 @@
 package com.android.server.wifi;
 
 import android.annotation.NonNull;
-import android.app.Notification;
 import android.app.NotificationManager;
-import android.app.TaskStackBuilder;
+import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
+import android.content.IntentFilter;
 import android.database.ContentObserver;
 import android.net.wifi.ScanResult;
-import android.net.wifi.WifiManager;
 import android.os.Handler;
 import android.os.Looper;
-import android.os.Message;
 import android.os.UserHandle;
 import android.os.UserManager;
 import android.provider.Settings;
 
-import com.android.internal.notification.SystemNotificationChannels;
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
 
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
@@ -43,69 +42,82 @@
  * @hide
  */
 public class OpenNetworkNotifier {
-    /**
-     * 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 =
-            com.android.internal.R.drawable.stat_notify_wifi_in_range;
-    /**
-     * When a notification is shown, we wait this amount before possibly showing it again.
-     */
-    private final long mNotificationRepeatDelay;
 
-    /** Whether the user has set the setting to show the 'available networks' notification. */
-    private boolean mSettingEnabled;
+    static final String ACTION_USER_DISMISSED_NOTIFICATION =
+            "com.android.server.wifi.OpenNetworkNotifier.USER_DISMISSED_NOTIFICATION";
+    static final String ACTION_USER_TAPPED_CONTENT =
+            "com.android.server.wifi.OpenNetworkNotifier.USER_TAPPED_CONTENT";
 
     /**
-     * Observes the user setting to keep {@link #mSettingEnabled} in sync.
-     */
-    private NotificationEnabledSettingObserver mNotificationEnabledSettingObserver;
-
-    /**
-     * The {@link System#currentTimeMillis()} must be at least this value for us
+     * The {@link Clock#getWallClockMillis()} must be at least this value for us
      * to show the notification again.
      */
     private long mNotificationRepeatTime;
     /**
-     * The Notification object given to the NotificationManager.
+     * When a notification is shown, we wait this amount before possibly showing it again.
      */
-    private Notification.Builder mNotificationBuilder;
-    /**
-     * Whether the notification is being shown, as set by us. That is, if the
-     * user cancels the notification, we will not receive the callback so this
-     * will still be true. We only guarantee if this is false, then the
-     * notification is not showing.
-     */
+    private final long mNotificationRepeatDelay;
+    /** Default repeat delay in seconds. */
+    @VisibleForTesting
+    static final int DEFAULT_REPEAT_DELAY_SEC = 900;
+
+    /** Whether the user has set the setting to show the 'available networks' notification. */
+    private boolean mSettingEnabled;
+    /** Whether the notification is being shown. */
     private boolean mNotificationShown;
     /** Whether the screen is on or not. */
     private boolean mScreenOn;
 
     private final Context mContext;
+    private final Handler mHandler;
     private final FrameworkFacade mFrameworkFacade;
+    private final Clock mClock;
     private final OpenNetworkRecommender mOpenNetworkRecommender;
+    private final OpenNetworkNotificationBuilder mOpenNetworkNotificationBuilder;
+
     private ScanResult mRecommendedNetwork;
 
-    OpenNetworkNotifier(Context context,
-                        Looper looper,
-                        FrameworkFacade framework,
-                        Notification.Builder builder,
-                        OpenNetworkRecommender recommender) {
+    OpenNetworkNotifier(
+            Context context,
+            Looper looper,
+            FrameworkFacade framework,
+            Clock clock,
+            OpenNetworkRecommender openNetworkRecommender) {
         mContext = context;
+        mHandler = new Handler(looper);
         mFrameworkFacade = framework;
-        mNotificationBuilder = builder;
-        mOpenNetworkRecommender = recommender;
-
+        mClock = clock;
+        mOpenNetworkRecommender = openNetworkRecommender;
+        mOpenNetworkNotificationBuilder = new OpenNetworkNotificationBuilder(context, framework);
         mScreenOn = false;
 
         // Setting is in seconds
         mNotificationRepeatDelay = mFrameworkFacade.getIntegerSetting(context,
-                Settings.Global.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000L;
-        mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(
-                new Handler(looper));
-        mNotificationEnabledSettingObserver.register();
+                Settings.Global.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY,
+                DEFAULT_REPEAT_DELAY_SEC) * 1000L;
+        NotificationEnabledSettingObserver settingObserver = new NotificationEnabledSettingObserver(
+                mHandler);
+        settingObserver.register();
+
+        IntentFilter filter = new IntentFilter();
+        filter.addAction(ACTION_USER_DISMISSED_NOTIFICATION);
+        filter.addAction(ACTION_USER_TAPPED_CONTENT);
+        mContext.registerReceiver(
+                mBroadcastReceiver, filter, null /* broadcastPermission */, mHandler);
     }
 
+    private final BroadcastReceiver mBroadcastReceiver =
+            new BroadcastReceiver() {
+                @Override
+                public void onReceive(Context context, Intent intent) {
+                    if (ACTION_USER_TAPPED_CONTENT.equals(intent.getAction())) {
+                        handleUserClickedContentAction();
+                    } else if (ACTION_USER_DISMISSED_NOTIFICATION.equals(intent.getAction())) {
+                        handleUserDismissedAction();
+                    }
+                }
+            };
+
     /**
      * Clears the pending notification. This is called by {@link WifiConnectivityManager} on stop.
      *
@@ -115,7 +127,12 @@
         if (resetRepeatDelay) {
             mNotificationRepeatTime = 0;
         }
-        setNotificationVisible(false, 0, false, 0);
+
+        if (mNotificationShown) {
+            getNotificationManager().cancel(SystemMessage.NOTE_NETWORK_AVAILABLE);
+            mRecommendedNetwork = null;
+            mNotificationShown = false;
+        }
     }
 
     private boolean isControllerEnabled() {
@@ -150,7 +167,7 @@
         mRecommendedNetwork = mOpenNetworkRecommender.recommendNetwork(
                 availableNetworks, mRecommendedNetwork);
 
-        setNotificationVisible(true, availableNetworks.size(), false, 0);
+        postNotification(availableNetworks.size());
     }
 
     /** Handles screen state changes. */
@@ -158,80 +175,44 @@
         mScreenOn = screenOn;
     }
 
-    /**
-     * Display or don't display a notification that there are open Wi-Fi networks.
-     * @param visible {@code true} if notification should be visible, {@code false} otherwise
-     * @param numNetworks the number networks seen
-     * @param force {@code true} to force notification to be shown/not-shown,
-     * even if it is already shown/not-shown.
-     * @param delay time in milliseconds after which the notification should be made
-     * visible or invisible.
-     */
-    private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
-            int delay) {
+    private NotificationManager getNotificationManager() {
+        return (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
+    }
 
-        // 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)
-
-        // If it should be hidden and it is already hidden, then noop
-        if (!visible && !mNotificationShown && !force) {
+    private void postNotification(int numNetworks) {
+        // Not enough time has passed to show the notification again
+        if (mClock.getWallClockMillis() < mNotificationRepeatTime) {
             return;
         }
 
-        NotificationManager notificationManager = (NotificationManager) mContext
-                .getSystemService(Context.NOTIFICATION_SERVICE);
+        getNotificationManager().notify(
+                SystemMessage.NOTE_NETWORK_AVAILABLE,
+                mOpenNetworkNotificationBuilder.createOpenNetworkAvailableNotification(
+                        numNetworks));
+        mNotificationShown = true;
+        mNotificationRepeatTime = mClock.getWallClockMillis() + mNotificationRepeatDelay;
+    }
 
-        Message message;
-        if (visible) {
+    /** Opens Wi-Fi picker. */
+    private void handleUserClickedContentAction() {
+        mNotificationShown = false;
+        mContext.startActivity(
+                new Intent(Settings.ACTION_WIFI_SETTINGS)
+                        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
+    }
 
-            // Not enough time has passed to show the notification again
-            if (System.currentTimeMillis() < mNotificationRepeatTime) {
-                return;
-            }
-
-            if (mNotificationBuilder == null) {
-                // Cache the Notification builder object.
-                mNotificationBuilder = new Notification.Builder(mContext,
-                        SystemNotificationChannels.NETWORK_AVAILABLE)
-                        .setWhen(0)
-                        .setSmallIcon(ICON_NETWORKS_AVAILABLE)
-                        .setAutoCancel(true)
-                        .setContentIntent(TaskStackBuilder.create(mContext)
-                                .addNextIntentWithParentStack(
-                                        new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK))
-                                .getPendingIntent(0, 0, null, UserHandle.CURRENT))
-                        .setColor(mContext.getResources().getColor(
-                                com.android.internal.R.color.system_notification_accent_color));
-            }
-
-            CharSequence title = mContext.getResources().getQuantityText(
-                    com.android.internal.R.plurals.wifi_available, numNetworks);
-            CharSequence details = mContext.getResources().getQuantityText(
-                    com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
-            mNotificationBuilder.setTicker(title);
-            mNotificationBuilder.setContentTitle(title);
-            mNotificationBuilder.setContentText(details);
-
-            mNotificationRepeatTime = System.currentTimeMillis() + mNotificationRepeatDelay;
-
-            notificationManager.notifyAsUser(null, ICON_NETWORKS_AVAILABLE,
-                    mNotificationBuilder.build(), UserHandle.ALL);
-        } else {
-            notificationManager.cancelAsUser(null, ICON_NETWORKS_AVAILABLE, UserHandle.ALL);
-        }
-
-        mNotificationShown = visible;
+    /** A delay is set before the next shown notification after user dismissal. */
+    private void handleUserDismissedAction() {
+        mNotificationShown = false;
     }
 
     /** Dump ONA controller state. */
     public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
         pw.println("OpenNetworkNotifier: ");
         pw.println("mSettingEnabled " + mSettingEnabled);
-        pw.println("mNotificationRepeatTime " + mNotificationRepeatTime);
-        pw.println("mNotificationShown " + mNotificationShown);
+        pw.println("currentTime: " + mClock.getWallClockMillis());
+        pw.println("mNotificationRepeatTime: " + mNotificationRepeatTime);
+        pw.println("mNotificationShown: " + mNotificationShown);
     }
 
     private class NotificationEnabledSettingObserver extends ContentObserver {
diff --git a/service/java/com/android/server/wifi/WifiInjector.java b/service/java/com/android/server/wifi/WifiInjector.java
index 1be3d78..60c5d2f 100644
--- a/service/java/com/android/server/wifi/WifiInjector.java
+++ b/service/java/com/android/server/wifi/WifiInjector.java
@@ -232,7 +232,7 @@
                 new WrongPasswordNotifier(mContext, mFrameworkFacade));
         mCertManager = new WifiCertManager(mContext);
         mOpenNetworkNotifier = new OpenNetworkNotifier(mContext,
-                mWifiStateMachineHandlerThread.getLooper(), mFrameworkFacade, null,
+                mWifiStateMachineHandlerThread.getLooper(), mFrameworkFacade, mClock,
                 new OpenNetworkRecommender());
         mLockManager = new WifiLockManager(mContext, BatteryStatsService.getService());
         mWifiController = new WifiController(mContext, mWifiStateMachine, mSettingsStore,
diff --git a/tests/wifitests/src/com/android/server/wifi/OpenNetworkNotifierTest.java b/tests/wifitests/src/com/android/server/wifi/OpenNetworkNotifierTest.java
index f620c76..29c068d 100644
--- a/tests/wifitests/src/com/android/server/wifi/OpenNetworkNotifierTest.java
+++ b/tests/wifitests/src/com/android/server/wifi/OpenNetworkNotifierTest.java
@@ -16,16 +16,21 @@
 
 package com.android.server.wifi;
 
+import static com.android.server.wifi.OpenNetworkNotifier.DEFAULT_REPEAT_DELAY_SEC;
+
 import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.Mockito.anyInt;
-import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 import android.app.Notification;
 import android.app.NotificationManager;
+import android.content.BroadcastReceiver;
 import android.content.Context;
+import android.content.Intent;
 import android.content.res.Resources;
 import android.net.wifi.ScanResult;
 import android.os.UserHandle;
@@ -35,6 +40,8 @@
 
 import org.junit.Before;
 import org.junit.Test;
+import org.mockito.Answers;
+import org.mockito.ArgumentCaptor;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
@@ -52,10 +59,13 @@
     @Mock private Context mContext;
     @Mock private Resources mResources;
     @Mock private FrameworkFacade mFrameworkFacade;
+    @Mock private Clock mClock;
+    @Mock(answer = Answers.RETURNS_DEEP_STUBS) private Notification.Builder mNotificationBuilder;
     @Mock private NotificationManager mNotificationManager;
     @Mock private OpenNetworkRecommender mOpenNetworkRecommender;
     @Mock private UserManager mUserManager;
     private OpenNetworkNotifier mNotificationController;
+    private BroadcastReceiver mBroadcastReceiver;
     private ScanResult mDummyNetwork;
 
 
@@ -67,6 +77,11 @@
                 .thenReturn(mNotificationManager);
         when(mFrameworkFacade.getIntegerSetting(mContext,
                 Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1)).thenReturn(1);
+        when(mFrameworkFacade.getIntegerSetting(mContext,
+                Settings.Global.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, DEFAULT_REPEAT_DELAY_SEC))
+                .thenReturn(DEFAULT_REPEAT_DELAY_SEC);
+        when(mFrameworkFacade.makeNotificationBuilder(any(), anyString()))
+                .thenReturn(mNotificationBuilder);
         when(mContext.getSystemService(Context.USER_SERVICE))
                 .thenReturn(mUserManager);
         when(mContext.getResources()).thenReturn(mResources);
@@ -79,7 +94,11 @@
         TestLooper mock_looper = new TestLooper();
         mNotificationController = new OpenNetworkNotifier(
                 mContext, mock_looper.getLooper(), mFrameworkFacade,
-                mock(Notification.Builder.class), mOpenNetworkRecommender);
+                mClock, mOpenNetworkRecommender);
+        ArgumentCaptor<BroadcastReceiver> broadcastReceiverCaptor =
+                ArgumentCaptor.forClass(BroadcastReceiver.class);
+        verify(mContext).registerReceiver(broadcastReceiverCaptor.capture(), any(), any(), any());
+        mBroadcastReceiver = broadcastReceiverCaptor.getValue();
         mNotificationController.handleScreenStateChanged(true);
     }
 
@@ -97,7 +116,7 @@
         mNotificationController.handleScanResults(createOpenScanResults());
 
         verify(mOpenNetworkRecommender).recommendNetwork(any(), any());
-        verify(mNotificationManager).notifyAsUser(any(), anyInt(), any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
     }
 
     /**
@@ -108,7 +127,7 @@
         mNotificationController.handleScanResults(new ArrayList<>());
 
         verify(mOpenNetworkRecommender, never()).recommendNetwork(any(), any());
-        verify(mNotificationManager, never()).notifyAsUser(any(), anyInt(), any(), any());
+        verify(mNotificationManager, never()).notify(anyInt(), any());
     }
 
     /**
@@ -120,11 +139,11 @@
         mNotificationController.handleScanResults(createOpenScanResults());
 
         verify(mOpenNetworkRecommender).recommendNetwork(any(), any());
-        verify(mNotificationManager).notifyAsUser(any(), anyInt(), any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
 
         mNotificationController.handleScanResults(new ArrayList<>());
 
-        verify(mNotificationManager).cancelAsUser(any(), anyInt(), any());
+        verify(mNotificationManager).cancel(anyInt());
     }
     /**
      * When a notification is showing, screen is off, and scan results with no open networks are
@@ -135,12 +154,12 @@
         mNotificationController.handleScanResults(createOpenScanResults());
 
         verify(mOpenNetworkRecommender).recommendNetwork(any(), any());
-        verify(mNotificationManager).notifyAsUser(any(), anyInt(), any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
 
         mNotificationController.handleScreenStateChanged(false);
         mNotificationController.handleScanResults(new ArrayList<>());
 
-        verify(mNotificationManager).cancelAsUser(any(), anyInt(), any());
+        verify(mNotificationManager).cancel(anyInt());
     }
 
     /**
@@ -152,7 +171,7 @@
         mNotificationController.handleScanResults(createOpenScanResults());
 
         verify(mOpenNetworkRecommender).recommendNetwork(any(), any());
-        verify(mNotificationManager).notifyAsUser(any(), anyInt(), any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
     }
 
     /**
@@ -164,11 +183,11 @@
         mNotificationController.handleScanResults(createOpenScanResults());
 
         verify(mOpenNetworkRecommender).recommendNetwork(any(), any());
-        verify(mNotificationManager).notifyAsUser(any(), anyInt(), any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
 
         mNotificationController.clearPendingNotification(true);
 
-        verify(mNotificationManager).cancelAsUser(any(), anyInt(), any());
+        verify(mNotificationManager).cancel(anyInt());
     }
 
     /**
@@ -179,7 +198,7 @@
     public void clearPendingNotification_doesNotClearNotificationIfNoneShowing() {
         mNotificationController.clearPendingNotification(true);
 
-        verify(mNotificationManager, never()).cancelAsUser(any(), anyInt(), any());
+        verify(mNotificationManager, never()).cancel(anyInt());
     }
 
     /**
@@ -192,7 +211,85 @@
         mNotificationController.handleScanResults(createOpenScanResults());
 
         verify(mOpenNetworkRecommender, never()).recommendNetwork(any(), any());
-        verify(mNotificationManager, never()).notifyAsUser(any(), anyInt(), any(), any());
+        verify(mNotificationManager, never()).notify(anyInt(), any());
+    }
+
+    /**
+     * When a notification is posted and cleared without reseting delay, the next scan with open
+     * networks should not post another notification.
+     */
+    @Test
+    public void postNotification_clearNotificationWithoutDelayReset_shouldNotPostNotification() {
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        verify(mOpenNetworkRecommender).recommendNetwork(any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
+
+        mNotificationController.clearPendingNotification(false);
+
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        // Recommendation made twice but no new notification posted.
+        verify(mOpenNetworkRecommender, times(2)).recommendNetwork(any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
+        verify(mNotificationManager).cancel(anyInt());
+    }
+
+    /**
+     * When a notification is posted and cleared without reseting delay, the next scan with open
+     * networks should post a notification.
+     */
+    @Test
+    public void postNotification_clearNotificationWithDelayReset_shouldPostNotification() {
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        verify(mOpenNetworkRecommender).recommendNetwork(any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
+
+        mNotificationController.clearPendingNotification(true);
+
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        verify(mOpenNetworkRecommender, times(2)).recommendNetwork(any(), any());
+        verify(mNotificationManager, times(2)).notify(anyInt(), any());
+    }
+
+    /**
+     * When a notification is tapped, open Wi-Fi settings.
+     */
+    @Test
+    public void notificationTap_opensWifiSettings() {
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        verify(mOpenNetworkRecommender).recommendNetwork(any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
+
+        mBroadcastReceiver.onReceive(
+                mContext, new Intent(OpenNetworkNotifier.ACTION_USER_TAPPED_CONTENT));
+
+        verify(mContext).startActivity(any());
+    }
+
+    /**
+     * When a notification is posted and cleared without reseting delay, after the delay has passed
+     * the next scan with open networks should post a notification.
+     */
+    @Test
+    public void delaySet_delayPassed_shouldPostNotification() {
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        verify(mOpenNetworkRecommender).recommendNetwork(any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
+
+        mNotificationController.clearPendingNotification(false);
+
+        // twice the delay time passed
+        when(mClock.getWallClockMillis()).thenReturn(DEFAULT_REPEAT_DELAY_SEC * 1000L * 2);
+
+        mNotificationController.handleScanResults(createOpenScanResults());
+
+        verify(mOpenNetworkRecommender, times(2)).recommendNetwork(any(), any());
+        verify(mNotificationManager, times(2)).notify(anyInt(), any());
     }
 
     /** Verifies that {@link UserManager#DISALLOW_CONFIG_WIFI} disables the feature. */
@@ -204,7 +301,7 @@
         mNotificationController.handleScanResults(createOpenScanResults());
 
         verify(mOpenNetworkRecommender, never()).recommendNetwork(any(), any());
-        verify(mNotificationManager, never()).notifyAsUser(any(), anyInt(), any(), any());
+        verify(mNotificationManager, never()).notify(anyInt(), any());
     }
 
     /** Verifies that {@link UserManager#DISALLOW_CONFIG_WIFI} clears the showing notification. */
@@ -213,13 +310,13 @@
         mNotificationController.handleScanResults(createOpenScanResults());
 
         verify(mOpenNetworkRecommender).recommendNetwork(any(), any());
-        verify(mNotificationManager).notifyAsUser(any(), anyInt(), any(), any());
+        verify(mNotificationManager).notify(anyInt(), any());
 
         when(mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, UserHandle.CURRENT))
                 .thenReturn(true);
 
         mNotificationController.handleScanResults(createOpenScanResults());
 
-        verify(mNotificationManager).cancelAsUser(any(), anyInt(), any());
+        verify(mNotificationManager).cancel(anyInt());
     }
 }