diff options
author | Amin Shaikh <ashaikh@google.com> | 2017-05-12 09:07:11 +0000 |
---|---|---|
committer | android-build-merger <android-build-merger@google.com> | 2017-05-12 09:07:11 +0000 |
commit | d97a85f3ae5f5ff8213827a4389ba188b99f528a (patch) | |
tree | 8096a8e32dd562a24a96ab8bc40c22d8eed91619 | |
parent | 7e672c90b423d9e49ed4ee56e1f49622a1e80e72 (diff) | |
parent | 1824dda8eeaec6038cb6c9af39c0b188cce605ad (diff) |
Merge changes from topic 'onarevert' into oc-dev am: 506d139a53
am: 1824dda8ee
Change-Id: I6549893819dff8f8e085f82321c1c5850e5c1165
4 files changed, 518 insertions, 0 deletions
diff --git a/service/java/com/android/server/wifi/WifiInjector.java b/service/java/com/android/server/wifi/WifiInjector.java index 99cf7a9ad..9e9824b71 100644 --- a/service/java/com/android/server/wifi/WifiInjector.java +++ b/service/java/com/android/server/wifi/WifiInjector.java @@ -86,6 +86,7 @@ public class WifiInjector { private final WifiStateMachine mWifiStateMachine; private final WifiSettingsStore mSettingsStore; private final WifiCertManager mCertManager; + private final WifiNotificationController mNotificationController; private final WifiLockManager mLockManager; private final WifiController mWifiController; private final WificondControl mWificondControl; @@ -220,6 +221,8 @@ public class WifiInjector { wifiStateMachineLooper, UserManager.get(mContext), this, mBackupManagerProxy, mCountryCode, mWifiNative); mCertManager = new WifiCertManager(mContext); + mNotificationController = new WifiNotificationController(mContext, + mWifiServiceHandlerThread.getLooper(), mFrameworkFacade, null, this); mLockManager = new WifiLockManager(mContext, BatteryStatsService.getService()); mWifiController = new WifiController(mContext, mWifiStateMachine, mSettingsStore, mLockManager, mWifiServiceHandlerThread.getLooper(), mFrameworkFacade); @@ -294,6 +297,10 @@ public class WifiInjector { return mCertManager; } + public WifiNotificationController getWifiNotificationController() { + return mNotificationController; + } + public WifiLockManager getWifiLockManager() { return mLockManager; } diff --git a/service/java/com/android/server/wifi/WifiNotificationController.java b/service/java/com/android/server/wifi/WifiNotificationController.java new file mode 100644 index 000000000..c8e5e908a --- /dev/null +++ b/service/java/com/android/server/wifi/WifiNotificationController.java @@ -0,0 +1,346 @@ +/* + * Copyright (C) 2013 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 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.NetworkInfo; +import android.net.wifi.ScanResult; +import android.net.wifi.WifiManager; +import android.net.wifi.WifiScanner; +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 java.io.FileDescriptor; +import java.io.PrintWriter; +import java.util.List; + +/** + * 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 = + 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 NOTIFICATION_REPEAT_DELAY_MS; + + /** + * 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 NotificationEnabledSettingObserver mNotificationEnabledSettingObserver; + + /** + * The {@link System#currentTimeMillis()} must be at least this value for us + * to show the notification again. + */ + private long mNotificationRepeatTime; + /** + * The Notification object given to the NotificationManager. + */ + 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 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; + + private final Context mContext; + private NetworkInfo mNetworkInfo; + private NetworkInfo.DetailedState mDetailedState; + private volatile int mWifiState; + private FrameworkFacade mFrameworkFacade; + private WifiInjector mWifiInjector; + private WifiScanner mWifiScanner; + + WifiNotificationController(Context context, + Looper looper, + FrameworkFacade framework, + Notification.Builder builder, + WifiInjector wifiInjector) { + mContext = context; + mFrameworkFacade = framework; + mNotificationBuilder = builder; + mWifiInjector = wifiInjector; + 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); + + mContext.registerReceiver( + new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + if (intent.getAction() + .equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) { + mWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, + WifiManager.WIFI_STATE_UNKNOWN); + 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; + // reset & clear notification on a network connect & disconnect + switch(mDetailedState) { + case CONNECTED: + case DISCONNECTED: + case CAPTIVE_PORTAL_CHECK: + resetNotification(); + break; + + 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)) { + if (mWifiScanner == null) { + mWifiScanner = mWifiInjector.getWifiScanner(); + } + checkAndSetNotification(mNetworkInfo, + mWifiScanner.getSingleScanResults()); + } + } + }, filter); + + // Setting is in seconds + NOTIFICATION_REPEAT_DELAY_MS = mFrameworkFacade.getIntegerSetting(context, + Settings.Global.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000L; + mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver( + new Handler(looper)); + mNotificationEnabledSettingObserver.register(); + } + + private synchronized 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 (UserManager.get(mContext) + .hasUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, UserHandle.CURRENT)) { + return; + } + + NetworkInfo.State state = NetworkInfo.State.DISCONNECTED; + if (networkInfo != null) + state = networkInfo.getState(); + + if ((state == NetworkInfo.State.DISCONNECTED) + || (state == NetworkInfo.State.UNKNOWN)) { + if (scanResults != null) { + int numOpenNetworks = 0; + for (int i = scanResults.size() - 1; i >= 0; i--) { + ScanResult scanResult = scanResults.get(i); + + //A capability of [ESS] represents an open access point + //that is available for an STA to connect + if (scanResult.capabilities != null && + scanResult.capabilities.equals("[ESS]")) { + numOpenNetworks++; + } + } + + if (numOpenNetworks > 0) { + if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) { + /* + * We've 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. + */ + setNotificationVisible(true, numOpenNetworks, false, 0); + } + return; + } + } + } + + // No open networks in range, remove the notification + setNotificationVisible(false, 0, false, 0); + } + + /** + * Clears variables related to tracking whether a notification has been + * shown recently and clears the current notification. + */ + private synchronized void resetNotification() { + mNotificationRepeatTime = 0; + mNumScansSinceNetworkStateChange = 0; + setNotificationVisible(false, 0, false, 0); + } + + /** + * 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) { + + // 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) { + return; + } + + NotificationManager notificationManager = (NotificationManager) mContext + .getSystemService(Context.NOTIFICATION_SERVICE); + + Message message; + if (visible) { + + // 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() + NOTIFICATION_REPEAT_DELAY_MS; + + notificationManager.notifyAsUser(null, ICON_NETWORKS_AVAILABLE, + mNotificationBuilder.build(), UserHandle.ALL); + } else { + notificationManager.cancelAsUser(null, ICON_NETWORKS_AVAILABLE, UserHandle.ALL); + } + + mNotificationShown = visible; + } + + 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 { + public NotificationEnabledSettingObserver(Handler handler) { + super(handler); + } + + public void register() { + mFrameworkFacade.registerContentObserver(mContext, Settings.Global.getUriFor( + Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON), true, this); + synchronized (WifiNotificationController.this) { + mNotificationEnabled = getValue(); + } + } + + @Override + public void onChange(boolean selfChange) { + super.onChange(selfChange); + + synchronized (WifiNotificationController.this) { + mNotificationEnabled = getValue(); + resetNotification(); + } + } + + private boolean getValue() { + return mFrameworkFacade.getIntegerSetting(mContext, + Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1; + } + } +} diff --git a/service/java/com/android/server/wifi/WifiServiceImpl.java b/service/java/com/android/server/wifi/WifiServiceImpl.java index 4aea04a4c..243034f14 100644 --- a/service/java/com/android/server/wifi/WifiServiceImpl.java +++ b/service/java/com/android/server/wifi/WifiServiceImpl.java @@ -155,6 +155,8 @@ public class WifiServiceImpl extends IWifiManager.Stub { // Debug counter tracking scan requests sent by WifiManager private int scanRequestCounter = 0; + /* Tracks the open wi-fi network notification */ + private WifiNotificationController mNotificationController; /* Polls traffic stats and notifies clients */ private WifiTrafficPoller mTrafficPoller; /* Tracks the persisted states for wi-fi & airplane mode */ @@ -359,6 +361,7 @@ public class WifiServiceImpl extends IWifiManager.Stub { mAppOps = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE); mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); mCertManager = mWifiInjector.getWifiCertManager(); + mNotificationController = mWifiInjector.getWifiNotificationController(); mWifiLockManager = mWifiInjector.getWifiLockManager(); mWifiMulticastLockManager = mWifiInjector.getWifiMulticastLockManager(); HandlerThread wifiServiceHandlerThread = mWifiInjector.getWifiServiceHandlerThread(); @@ -1888,6 +1891,7 @@ public class WifiServiceImpl extends IWifiManager.Stub { pw.println("mScanPending " + mScanPending); mWifiController.dump(fd, pw, args); mSettingsStore.dump(fd, pw, args); + mNotificationController.dump(fd, pw, args); mTrafficPoller.dump(fd, pw, args); pw.println(); pw.println("Locks held:"); diff --git a/tests/wifitests/src/com/android/server/wifi/WifiNotificationControllerTest.java b/tests/wifitests/src/com/android/server/wifi/WifiNotificationControllerTest.java new file mode 100644 index 000000000..f7b3bf6a1 --- /dev/null +++ b/tests/wifitests/src/com/android/server/wifi/WifiNotificationControllerTest.java @@ -0,0 +1,161 @@ +/* + * Copyright (C) 2016 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 org.mockito.Mockito.any; +import static org.mockito.Mockito.anyInt; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +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.IntentFilter; +import android.content.res.Resources; +import android.net.NetworkInfo; +import android.net.wifi.ScanResult; +import android.net.wifi.WifiManager; +import android.net.wifi.WifiScanner; +import android.os.UserHandle; +import android.os.UserManager; +import android.os.test.TestLooper; +import android.provider.Settings; +import android.test.suitebuilder.annotation.SmallTest; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.util.ArrayList; +import java.util.List; + +/** + * Unit tests for {@link com.android.server.wifi.WifiScanningServiceImpl}. + */ +@SmallTest +public class WifiNotificationControllerTest { + public static final String TAG = "WifiScanningServiceTest"; + + @Mock private Context mContext; + @Mock private Resources mResources; + @Mock private FrameworkFacade mFrameworkFacade; + @Mock private NotificationManager mNotificationManager; + @Mock private UserManager mUserManager; + @Mock private WifiInjector mWifiInjector; + @Mock private WifiScanner mWifiScanner; + WifiNotificationController mWifiNotificationController; + + /** + * Internal BroadcastReceiver that WifiNotificationController uses to listen for broadcasts + * this is initialized by calling startServiceAndLoadDriver + */ + BroadcastReceiver mBroadcastReceiver; + + /** Initialize objects before each test run. */ + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + when(mContext.getSystemService(Context.NOTIFICATION_SERVICE)) + .thenReturn(mNotificationManager); + + when(mFrameworkFacade.getIntegerSetting(mContext, + Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1)).thenReturn(1); + + when(mContext.getSystemService(Context.USER_SERVICE)) + .thenReturn(mUserManager); + when(mContext.getResources()).thenReturn(mResources); + + when(mWifiInjector.getWifiScanner()).thenReturn(mWifiScanner); + + TestLooper mock_looper = new TestLooper(); + mWifiNotificationController = new WifiNotificationController( + mContext, mock_looper.getLooper(), mFrameworkFacade, + mock(Notification.Builder.class), mWifiInjector); + ArgumentCaptor<BroadcastReceiver> broadcastReceiverCaptor = + ArgumentCaptor.forClass(BroadcastReceiver.class); + + verify(mContext) + .registerReceiver(broadcastReceiverCaptor.capture(), any(IntentFilter.class)); + mBroadcastReceiver = broadcastReceiverCaptor.getValue(); + } + + private void setOpenAccessPoint() { + List<ScanResult> scanResults = new ArrayList<>(); + ScanResult scanResult = new ScanResult(); + scanResult.capabilities = "[ESS]"; + scanResults.add(scanResult); + when(mWifiScanner.getSingleScanResults()).thenReturn(scanResults); + } + + /** Verifies that a notification is displayed (and retracted) given system events. */ + @Test + public void verifyNotificationDisplayed() throws Exception { + TestUtil.sendWifiStateChanged(mBroadcastReceiver, mContext, WifiManager.WIFI_STATE_ENABLED); + TestUtil.sendNetworkStateChanged(mBroadcastReceiver, mContext, + NetworkInfo.DetailedState.DISCONNECTED); + setOpenAccessPoint(); + + // The notification should not be displayed after only two scan results. + TestUtil.sendScanResultsAvailable(mBroadcastReceiver, mContext); + TestUtil.sendScanResultsAvailable(mBroadcastReceiver, mContext); + verify(mNotificationManager, never()) + .notifyAsUser(any(), anyInt(), any(), any(UserHandle.class)); + + // Changing to and from "SCANNING" state should not affect the counter. + TestUtil.sendNetworkStateChanged(mBroadcastReceiver, mContext, + NetworkInfo.DetailedState.SCANNING); + TestUtil.sendNetworkStateChanged(mBroadcastReceiver, mContext, + NetworkInfo.DetailedState.DISCONNECTED); + + // The third scan result notification will trigger the notification. + TestUtil.sendScanResultsAvailable(mBroadcastReceiver, mContext); + verify(mNotificationManager) + .notifyAsUser(any(), anyInt(), any(), any(UserHandle.class)); + verify(mNotificationManager, never()) + .cancelAsUser(any(), anyInt(), any(UserHandle.class)); + + // Changing network state should cause the notification to go away. + TestUtil.sendNetworkStateChanged(mBroadcastReceiver, mContext, + NetworkInfo.DetailedState.CONNECTED); + verify(mNotificationManager) + .cancelAsUser(any(), anyInt(), any(UserHandle.class)); + } + + @Test + public void verifyNotificationNotDisplayed_userHasDisallowConfigWifiRestriction() { + when(mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_WIFI, UserHandle.CURRENT)) + .thenReturn(true); + + TestUtil.sendWifiStateChanged(mBroadcastReceiver, mContext, WifiManager.WIFI_STATE_ENABLED); + TestUtil.sendNetworkStateChanged(mBroadcastReceiver, mContext, + NetworkInfo.DetailedState.DISCONNECTED); + setOpenAccessPoint(); + + // The notification should be displayed after three scan results. + TestUtil.sendScanResultsAvailable(mBroadcastReceiver, mContext); + TestUtil.sendScanResultsAvailable(mBroadcastReceiver, mContext); + TestUtil.sendScanResultsAvailable(mBroadcastReceiver, mContext); + + verify(mNotificationManager, never()) + .notifyAsUser(any(), anyInt(), any(), any(UserHandle.class)); + } +} |