blob: 1ffccdd334054faa28e5283708fa359dbe89f8cd [file] [log] [blame]
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09001/*
2 * Copyright (C) 2016 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.connectivity;
18
19import android.app.PendingIntent;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +090020import android.net.NetworkCapabilities;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +090021import android.content.ComponentName;
22import android.content.Context;
23import android.content.Intent;
24import android.os.UserHandle;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +090025import android.text.TextUtils;
26import android.util.Log;
27import android.util.SparseArray;
28import android.util.SparseIntArray;
29import android.util.SparseBooleanArray;
30import java.util.Arrays;
31import java.util.HashMap;
32
Hugo Benichia43a0952016-08-30 10:01:15 +090033import com.android.internal.annotations.VisibleForTesting;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +090034import com.android.internal.util.MessageUtils;
35import com.android.server.connectivity.NetworkNotificationManager;
36import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
37
38import static android.net.ConnectivityManager.NETID_UNSET;
39
40/**
41 * Class that monitors default network linger events and possibly notifies the user of network
42 * switches.
43 *
44 * This class is not thread-safe and all its methods must be called on the ConnectivityService
45 * handler thread.
46 */
47public class LingerMonitor {
48
49 private static final boolean DBG = true;
50 private static final boolean VDBG = false;
51 private static final String TAG = LingerMonitor.class.getSimpleName();
52
Hugo Benichia43a0952016-08-30 10:01:15 +090053 private static final HashMap<String, Integer> TRANSPORT_NAMES = makeTransportToNameMap();
54 @VisibleForTesting
55 public static final Intent CELLULAR_SETTINGS = new Intent().setComponent(new ComponentName(
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +090056 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
57
Hugo Benichia43a0952016-08-30 10:01:15 +090058 @VisibleForTesting
59 public static final int NOTIFY_TYPE_NONE = 0;
60 public static final int NOTIFY_TYPE_NOTIFICATION = 1;
61 public static final int NOTIFY_TYPE_TOAST = 2;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +090062
63 private static SparseArray<String> sNotifyTypeNames = MessageUtils.findMessageNames(
64 new Class[] { LingerMonitor.class }, new String[]{ "NOTIFY_TYPE_" });
65
66 private final Context mContext;
67 private final NetworkNotificationManager mNotifier;
68
69 /** Current notifications. Maps the netId we switched away from to the netId we switched to. */
70 private final SparseIntArray mNotifications = new SparseIntArray();
71
72 /** Whether we ever notified that we switched away from a particular network. */
73 private final SparseBooleanArray mEverNotified = new SparseBooleanArray();
74
75 public LingerMonitor(Context context, NetworkNotificationManager notifier) {
76 mContext = context;
77 mNotifier = notifier;
78 }
79
80 private static HashMap<String, Integer> makeTransportToNameMap() {
81 SparseArray<String> numberToName = MessageUtils.findMessageNames(
82 new Class[] { NetworkCapabilities.class }, new String[]{ "TRANSPORT_" });
83 HashMap<String, Integer> nameToNumber = new HashMap<>();
84 for (int i = 0; i < numberToName.size(); i++) {
85 // MessageUtils will fail to initialize if there are duplicate constant values, so there
86 // are no duplicates here.
87 nameToNumber.put(numberToName.valueAt(i), numberToName.keyAt(i));
88 }
89 return nameToNumber;
90 }
91
92 private static boolean hasTransport(NetworkAgentInfo nai, int transport) {
93 return nai.networkCapabilities.hasTransport(transport);
94 }
95
96 private int getNotificationSource(NetworkAgentInfo toNai) {
97 for (int i = 0; i < mNotifications.size(); i++) {
98 if (mNotifications.valueAt(i) == toNai.network.netId) {
99 return mNotifications.keyAt(i);
100 }
101 }
102 return NETID_UNSET;
103 }
104
105 private boolean everNotified(NetworkAgentInfo nai) {
106 return mEverNotified.get(nai.network.netId, false);
107 }
108
Hugo Benichia43a0952016-08-30 10:01:15 +0900109 @VisibleForTesting
110 public boolean isNotificationEnabled(NetworkAgentInfo fromNai, NetworkAgentInfo toNai) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900111 // TODO: Evaluate moving to CarrierConfigManager.
112 String[] notifySwitches = mContext.getResources().getStringArray(
113 com.android.internal.R.array.config_networkNotifySwitches);
114
115 if (VDBG) {
116 Log.d(TAG, "Notify on network switches: " + Arrays.toString(notifySwitches));
117 }
118
119 for (String notifySwitch : notifySwitches) {
120 if (TextUtils.isEmpty(notifySwitch)) continue;
121 String[] transports = notifySwitch.split("-", 2);
122 if (transports.length != 2) {
123 Log.e(TAG, "Invalid network switch notification configuration: " + notifySwitch);
124 continue;
125 }
Hugo Benichia43a0952016-08-30 10:01:15 +0900126 int fromTransport = TRANSPORT_NAMES.get("TRANSPORT_" + transports[0]);
127 int toTransport = TRANSPORT_NAMES.get("TRANSPORT_" + transports[1]);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900128 if (hasTransport(fromNai, fromTransport) && hasTransport(toNai, toTransport)) {
129 return true;
130 }
131 }
132
133 return false;
134 }
135
136 private void showNotification(NetworkAgentInfo fromNai, NetworkAgentInfo toNai) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900137 mNotifier.showNotification(fromNai.network.netId, NotificationType.NETWORK_SWITCH,
Hugo Benichia43a0952016-08-30 10:01:15 +0900138 fromNai, toNai, createNotificationIntent(), true);
139 }
140
141 @VisibleForTesting
142 protected PendingIntent createNotificationIntent() {
143 return PendingIntent.getActivityAsUser(mContext, 0, CELLULAR_SETTINGS,
144 PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900145 }
146
147 // Removes any notification that was put up as a result of switching to nai.
148 private void maybeStopNotifying(NetworkAgentInfo nai) {
149 int fromNetId = getNotificationSource(nai);
150 if (fromNetId != NETID_UNSET) {
151 mNotifications.delete(fromNetId);
152 mNotifier.clearNotification(fromNetId);
153 // Toasts can't be deleted.
154 }
155 }
156
157 // Notify the user of a network switch using a notification or a toast.
158 private void notify(NetworkAgentInfo fromNai, NetworkAgentInfo toNai, boolean forceToast) {
159 boolean notify = false;
160 int notifyType = mContext.getResources().getInteger(
161 com.android.internal.R.integer.config_networkNotifySwitchType);
162
163 if (notifyType == NOTIFY_TYPE_NOTIFICATION && forceToast) {
164 notifyType = NOTIFY_TYPE_TOAST;
165 }
166
167 switch (notifyType) {
168 case NOTIFY_TYPE_NONE:
169 break;
170 case NOTIFY_TYPE_NOTIFICATION:
171 showNotification(fromNai, toNai);
172 notify = true;
173 break;
174 case NOTIFY_TYPE_TOAST:
175 mNotifier.showToast(fromNai, toNai);
176 notify = true;
177 break;
178 default:
179 Log.e(TAG, "Unknown notify type " + notifyType);
180 }
181
182 if (VDBG) {
183 Log.d(TAG, "Notify type: " + sNotifyTypeNames.get(notifyType, "" + notifyType));
184 }
185
186 if (notify) {
187 if (DBG) {
188 Log.d(TAG, "Notifying switch from=" + fromNai.name() + " to=" + toNai.name() +
189 " type=" + sNotifyTypeNames.get(notifyType, "unknown(" + notifyType + ")"));
190 }
191 mNotifications.put(fromNai.network.netId, toNai.network.netId);
192 mEverNotified.put(fromNai.network.netId, true);
193 }
194 }
195
196 // The default network changed from fromNai to toNai due to a change in score.
197 public void noteLingerDefaultNetwork(NetworkAgentInfo fromNai, NetworkAgentInfo toNai) {
198 if (VDBG) {
199 Log.d(TAG, "noteLingerDefaultNetwork from=" + fromNai.name() +
200 " everValidated=" + fromNai.everValidated +
201 " lastValidated=" + fromNai.lastValidated +
202 " to=" + toNai.name());
203 }
204
205 // If we are currently notifying the user because the device switched to fromNai, now that
206 // we are switching away from it we should remove the notification. This includes the case
207 // where we switch back to toNai because its score improved again (e.g., because it regained
208 // Internet access).
209 maybeStopNotifying(fromNai);
210
211 // If this network never validated, don't notify. Otherwise, we could do things like:
212 //
213 // 1. Unvalidated wifi connects.
214 // 2. Unvalidated mobile data connects.
215 // 3. Cell validates, and we show a notification.
216 // or:
217 // 1. User connects to wireless printer.
218 // 2. User turns on cellular data.
219 // 3. We show a notification.
220 if (!fromNai.everValidated) return;
221
222 // If this network is a captive portal, don't notify. This cannot happen on initial connect
223 // to a captive portal, because the everValidated check above will fail. However, it can
224 // happen if the captive portal reasserts itself (e.g., because its timeout fires). In that
225 // case, as soon as the captive portal reasserts itself, we'll show a sign-in notification.
226 // We don't want to overwrite that notification with this one; the user has already been
227 // notified, and of the two, the captive portal notification is the more useful one because
228 // it allows the user to sign in to the captive portal. In this case, display a toast
229 // in addition to the captive portal notification.
230 //
231 // Note that if the network we switch to is already up when the captive portal reappears,
232 // this won't work because NetworkMonitor tells ConnectivityService that the network is
233 // unvalidated (causing a switch) before asking it to show the sign in notification. In this
234 // case, the toast won't show and we'll only display the sign in notification. This is the
235 // best we can do at this time.
236 boolean forceToast = fromNai.networkCapabilities.hasCapability(
237 NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL);
238
239 // Only show the notification once, in order to avoid irritating the user every time.
240 // TODO: should we do this?
241 if (everNotified(fromNai)) {
242 if (VDBG) {
243 Log.d(TAG, "Not notifying handover from " + fromNai.name() + ", already notified");
244 }
245 return;
246 }
247
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +0900248 // Only show the notification if we switched away because a network became unvalidated, not
249 // because its score changed.
250 // TODO: instead of just skipping notification, keep a note of it, and show it if it becomes
251 // unvalidated.
252 if (fromNai.lastValidated) return;
253
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900254 if (isNotificationEnabled(fromNai, toNai)) {
255 notify(fromNai, toNai, forceToast);
256 }
257 }
258
259 public void noteDisconnect(NetworkAgentInfo nai) {
260 mNotifications.delete(nai.network.netId);
261 mEverNotified.delete(nai.network.netId);
262 maybeStopNotifying(nai);
263 // No need to cancel notifications on nai: NetworkMonitor does that on disconnect.
264 }
265}