blob: dfc61d98c6049fac92854bcc548bf1e1b590f998 [file] [log] [blame]
Aaron Heuckrothe5bec152018-07-09 16:26:09 -04001/**
2 * Copyright (c) 2018, 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.notification;
18
19import static android.app.NotificationManager.IMPORTANCE_NONE;
20
21import android.annotation.IntDef;
22import android.annotation.NonNull;
23import android.app.Notification;
24import android.app.NotificationChannel;
25import android.app.NotificationChannelGroup;
26import android.app.NotificationManager;
27import android.content.Context;
28import android.content.pm.ApplicationInfo;
29import android.content.pm.PackageManager;
30import android.content.pm.ParceledListSlice;
31import android.metrics.LogMaker;
32import android.os.Build;
33import android.os.UserHandle;
34import android.provider.Settings;
35import android.service.notification.NotificationListenerService;
36import android.service.notification.RankingHelperProto;
37import android.text.TextUtils;
38import android.util.ArrayMap;
39import android.util.Slog;
40import android.util.SparseBooleanArray;
41import android.util.proto.ProtoOutputStream;
42
43import com.android.internal.R;
44import com.android.internal.annotations.VisibleForTesting;
45import com.android.internal.logging.MetricsLogger;
46import com.android.internal.util.Preconditions;
47import com.android.internal.util.XmlUtils;
48
49import org.json.JSONArray;
50import org.json.JSONException;
51import org.json.JSONObject;
52import org.xmlpull.v1.XmlPullParser;
53import org.xmlpull.v1.XmlPullParserException;
54import org.xmlpull.v1.XmlSerializer;
55
56import java.io.IOException;
57import java.io.PrintWriter;
58import java.util.ArrayList;
59import java.util.Arrays;
60import java.util.Collection;
61import java.util.List;
62import java.util.Map;
63import java.util.Objects;
64import java.util.concurrent.ConcurrentHashMap;
65
66public class PreferencesHelper implements RankingConfig {
67 private static final String TAG = "NotificationPrefHelper";
68 private static final int XML_VERSION = 1;
69
70 @VisibleForTesting
71 static final String TAG_RANKING = "ranking";
72 private static final String TAG_PACKAGE = "package";
73 private static final String TAG_CHANNEL = "channel";
74 private static final String TAG_GROUP = "channelGroup";
75
76 private static final String ATT_VERSION = "version";
77 private static final String ATT_NAME = "name";
78 private static final String ATT_UID = "uid";
79 private static final String ATT_ID = "id";
80 private static final String ATT_PRIORITY = "priority";
81 private static final String ATT_VISIBILITY = "visibility";
82 private static final String ATT_IMPORTANCE = "importance";
83 private static final String ATT_SHOW_BADGE = "show_badge";
84 private static final String ATT_APP_USER_LOCKED_FIELDS = "app_user_locked_fields";
85
86 private static final int DEFAULT_PRIORITY = Notification.PRIORITY_DEFAULT;
87 private static final int DEFAULT_VISIBILITY = NotificationManager.VISIBILITY_NO_OVERRIDE;
88 private static final int DEFAULT_IMPORTANCE = NotificationManager.IMPORTANCE_UNSPECIFIED;
89 private static final boolean DEFAULT_SHOW_BADGE = true;
90 /**
91 * Default value for what fields are user locked. See {@link LockableAppFields} for all lockable
92 * fields.
93 */
94 private static final int DEFAULT_LOCKED_APP_FIELDS = 0;
95
96 /**
97 * All user-lockable fields for a given application.
98 */
99 @IntDef({LockableAppFields.USER_LOCKED_IMPORTANCE})
100 public @interface LockableAppFields {
101 int USER_LOCKED_IMPORTANCE = 0x00000001;
102 }
103
104 // pkg|uid => PackagePreferences
105 private final ArrayMap<String, PackagePreferences> mPackagePreferencess = new ArrayMap<>();
106 // pkg => PackagePreferences
107 private final ArrayMap<String, PackagePreferences> mRestoredWithoutUids = new ArrayMap<>();
108
109
110 private final Context mContext;
111 private final PackageManager mPm;
112 private final RankingHandler mRankingHandler;
113 private final ZenModeHelper mZenModeHelper;
114
115 private SparseBooleanArray mBadgingEnabled;
116 private boolean mAreChannelsBypassingDnd;
117
118
119 public PreferencesHelper(Context context, PackageManager pm, RankingHandler rankingHandler,
120 ZenModeHelper zenHelper) {
121 mContext = context;
122 mZenModeHelper = zenHelper;
123 mRankingHandler = rankingHandler;
124 mPm = pm;
125
126 updateBadgingEnabled();
127
128 mAreChannelsBypassingDnd = (mZenModeHelper.getNotificationPolicy().state &
129 NotificationManager.Policy.STATE_CHANNELS_BYPASSING_DND) == 1;
130 updateChannelsBypassingDnd();
131
132 }
133
134 public void readXml(XmlPullParser parser, boolean forRestore)
135 throws XmlPullParserException, IOException {
136 int type = parser.getEventType();
137 if (type != XmlPullParser.START_TAG) return;
138 String tag = parser.getName();
139 if (!TAG_RANKING.equals(tag)) return;
140 // Clobber groups and channels with the xml, but don't delete other data that wasn't present
141 // at the time of serialization.
142 mRestoredWithoutUids.clear();
143 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
144 tag = parser.getName();
145 if (type == XmlPullParser.END_TAG && TAG_RANKING.equals(tag)) {
146 return;
147 }
148 if (type == XmlPullParser.START_TAG) {
149 if (TAG_PACKAGE.equals(tag)) {
150 int uid = XmlUtils.readIntAttribute(parser, ATT_UID,
151 PackagePreferences.UNKNOWN_UID);
152 String name = parser.getAttributeValue(null, ATT_NAME);
153 if (!TextUtils.isEmpty(name)) {
154 if (forRestore) {
155 try {
156 //TODO: http://b/22388012
157 uid = mPm.getPackageUidAsUser(name,
158 UserHandle.USER_SYSTEM);
159 } catch (PackageManager.NameNotFoundException e) {
160 // noop
161 }
162 }
163
164 PackagePreferences r = getOrCreatePackagePreferences(name, uid,
165 XmlUtils.readIntAttribute(
166 parser, ATT_IMPORTANCE, DEFAULT_IMPORTANCE),
167 XmlUtils.readIntAttribute(parser, ATT_PRIORITY, DEFAULT_PRIORITY),
168 XmlUtils.readIntAttribute(
169 parser, ATT_VISIBILITY, DEFAULT_VISIBILITY),
170 XmlUtils.readBooleanAttribute(
171 parser, ATT_SHOW_BADGE, DEFAULT_SHOW_BADGE));
172 r.importance = XmlUtils.readIntAttribute(
173 parser, ATT_IMPORTANCE, DEFAULT_IMPORTANCE);
174 r.priority = XmlUtils.readIntAttribute(
175 parser, ATT_PRIORITY, DEFAULT_PRIORITY);
176 r.visibility = XmlUtils.readIntAttribute(
177 parser, ATT_VISIBILITY, DEFAULT_VISIBILITY);
178 r.showBadge = XmlUtils.readBooleanAttribute(
179 parser, ATT_SHOW_BADGE, DEFAULT_SHOW_BADGE);
180 r.lockedAppFields = XmlUtils.readIntAttribute(parser,
181 ATT_APP_USER_LOCKED_FIELDS, DEFAULT_LOCKED_APP_FIELDS);
182
183 final int innerDepth = parser.getDepth();
184 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
185 && (type != XmlPullParser.END_TAG
186 || parser.getDepth() > innerDepth)) {
187 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
188 continue;
189 }
190
191 String tagName = parser.getName();
192 // Channel groups
193 if (TAG_GROUP.equals(tagName)) {
194 String id = parser.getAttributeValue(null, ATT_ID);
195 CharSequence groupName = parser.getAttributeValue(null, ATT_NAME);
196 if (!TextUtils.isEmpty(id)) {
197 NotificationChannelGroup group
198 = new NotificationChannelGroup(id, groupName);
199 group.populateFromXml(parser);
200 r.groups.put(id, group);
201 }
202 }
203 // Channels
204 if (TAG_CHANNEL.equals(tagName)) {
205 String id = parser.getAttributeValue(null, ATT_ID);
206 String channelName = parser.getAttributeValue(null, ATT_NAME);
207 int channelImportance = XmlUtils.readIntAttribute(
208 parser, ATT_IMPORTANCE, DEFAULT_IMPORTANCE);
209 if (!TextUtils.isEmpty(id) && !TextUtils.isEmpty(channelName)) {
210 NotificationChannel channel = new NotificationChannel(id,
211 channelName, channelImportance);
212 if (forRestore) {
213 channel.populateFromXmlForRestore(parser, mContext);
214 } else {
215 channel.populateFromXml(parser);
216 }
217 r.channels.put(id, channel);
218 }
219 }
220 }
221
222 try {
223 deleteDefaultChannelIfNeeded(r);
224 } catch (PackageManager.NameNotFoundException e) {
225 Slog.e(TAG, "deleteDefaultChannelIfNeeded - Exception: " + e);
226 }
227 }
228 }
229 }
230 }
231 throw new IllegalStateException("Failed to reach END_DOCUMENT");
232 }
233
234 private PackagePreferences getPackagePreferences(String pkg, int uid) {
235 final String key = packagePreferencesKey(pkg, uid);
236 synchronized (mPackagePreferencess) {
237 return mPackagePreferencess.get(key);
238 }
239 }
240
241 private PackagePreferences getOrCreatePackagePreferences(String pkg, int uid) {
242 return getOrCreatePackagePreferences(pkg, uid,
243 DEFAULT_IMPORTANCE, DEFAULT_PRIORITY, DEFAULT_VISIBILITY, DEFAULT_SHOW_BADGE);
244 }
245
246 private PackagePreferences getOrCreatePackagePreferences(String pkg, int uid, int importance,
247 int priority, int visibility, boolean showBadge) {
248 final String key = packagePreferencesKey(pkg, uid);
249 synchronized (mPackagePreferencess) {
250 PackagePreferences
251 r = (uid == PackagePreferences.UNKNOWN_UID) ? mRestoredWithoutUids.get(pkg)
252 : mPackagePreferencess.get(key);
253 if (r == null) {
254 r = new PackagePreferences();
255 r.pkg = pkg;
256 r.uid = uid;
257 r.importance = importance;
258 r.priority = priority;
259 r.visibility = visibility;
260 r.showBadge = showBadge;
261
262 try {
263 createDefaultChannelIfNeeded(r);
264 } catch (PackageManager.NameNotFoundException e) {
265 Slog.e(TAG, "createDefaultChannelIfNeeded - Exception: " + e);
266 }
267
268 if (r.uid == PackagePreferences.UNKNOWN_UID) {
269 mRestoredWithoutUids.put(pkg, r);
270 } else {
271 mPackagePreferencess.put(key, r);
272 }
273 }
274 return r;
275 }
276 }
277
278 private boolean shouldHaveDefaultChannel(PackagePreferences r) throws
279 PackageManager.NameNotFoundException {
280 final int userId = UserHandle.getUserId(r.uid);
281 final ApplicationInfo applicationInfo =
282 mPm.getApplicationInfoAsUser(r.pkg, 0, userId);
283 if (applicationInfo.targetSdkVersion >= Build.VERSION_CODES.O) {
284 // O apps should not have the default channel.
285 return false;
286 }
287
288 // Otherwise, this app should have the default channel.
289 return true;
290 }
291
292 private void deleteDefaultChannelIfNeeded(PackagePreferences r) throws
293 PackageManager.NameNotFoundException {
294 if (!r.channels.containsKey(NotificationChannel.DEFAULT_CHANNEL_ID)) {
295 // Not present
296 return;
297 }
298
299 if (shouldHaveDefaultChannel(r)) {
300 // Keep the default channel until upgraded.
301 return;
302 }
303
304 // Remove Default Channel.
305 r.channels.remove(NotificationChannel.DEFAULT_CHANNEL_ID);
306 }
307
308 private void createDefaultChannelIfNeeded(PackagePreferences r) throws
309 PackageManager.NameNotFoundException {
310 if (r.channels.containsKey(NotificationChannel.DEFAULT_CHANNEL_ID)) {
311 r.channels.get(NotificationChannel.DEFAULT_CHANNEL_ID).setName(mContext.getString(
312 com.android.internal.R.string.default_notification_channel_label));
313 return;
314 }
315
316 if (!shouldHaveDefaultChannel(r)) {
317 // Keep the default channel until upgraded.
318 return;
319 }
320
321 // Create Default Channel
322 NotificationChannel channel;
323 channel = new NotificationChannel(
324 NotificationChannel.DEFAULT_CHANNEL_ID,
325 mContext.getString(R.string.default_notification_channel_label),
326 r.importance);
327 channel.setBypassDnd(r.priority == Notification.PRIORITY_MAX);
328 channel.setLockscreenVisibility(r.visibility);
329 if (r.importance != NotificationManager.IMPORTANCE_UNSPECIFIED) {
330 channel.lockFields(NotificationChannel.USER_LOCKED_IMPORTANCE);
331 }
332 if (r.priority != DEFAULT_PRIORITY) {
333 channel.lockFields(NotificationChannel.USER_LOCKED_PRIORITY);
334 }
335 if (r.visibility != DEFAULT_VISIBILITY) {
336 channel.lockFields(NotificationChannel.USER_LOCKED_VISIBILITY);
337 }
338 r.channels.put(channel.getId(), channel);
339 }
340
341 public void writeXml(XmlSerializer out, boolean forBackup) throws IOException {
342 out.startTag(null, TAG_RANKING);
343 out.attribute(null, ATT_VERSION, Integer.toString(XML_VERSION));
344
345 synchronized (mPackagePreferencess) {
346 final int N = mPackagePreferencess.size();
347 for (int i = 0; i < N; i++) {
348 final PackagePreferences r = mPackagePreferencess.valueAt(i);
349 //TODO: http://b/22388012
350 if (forBackup && UserHandle.getUserId(r.uid) != UserHandle.USER_SYSTEM) {
351 continue;
352 }
353 final boolean hasNonDefaultSettings =
354 r.importance != DEFAULT_IMPORTANCE
355 || r.priority != DEFAULT_PRIORITY
356 || r.visibility != DEFAULT_VISIBILITY
357 || r.showBadge != DEFAULT_SHOW_BADGE
358 || r.lockedAppFields != DEFAULT_LOCKED_APP_FIELDS
359 || r.channels.size() > 0
360 || r.groups.size() > 0;
361 if (hasNonDefaultSettings) {
362 out.startTag(null, TAG_PACKAGE);
363 out.attribute(null, ATT_NAME, r.pkg);
364 if (r.importance != DEFAULT_IMPORTANCE) {
365 out.attribute(null, ATT_IMPORTANCE, Integer.toString(r.importance));
366 }
367 if (r.priority != DEFAULT_PRIORITY) {
368 out.attribute(null, ATT_PRIORITY, Integer.toString(r.priority));
369 }
370 if (r.visibility != DEFAULT_VISIBILITY) {
371 out.attribute(null, ATT_VISIBILITY, Integer.toString(r.visibility));
372 }
373 out.attribute(null, ATT_SHOW_BADGE, Boolean.toString(r.showBadge));
374 out.attribute(null, ATT_APP_USER_LOCKED_FIELDS,
375 Integer.toString(r.lockedAppFields));
376
377 if (!forBackup) {
378 out.attribute(null, ATT_UID, Integer.toString(r.uid));
379 }
380
381 for (NotificationChannelGroup group : r.groups.values()) {
382 group.writeXml(out);
383 }
384
385 for (NotificationChannel channel : r.channels.values()) {
386 if (forBackup) {
387 if (!channel.isDeleted()) {
388 channel.writeXmlForBackup(out, mContext);
389 }
390 } else {
391 channel.writeXml(out);
392 }
393 }
394
395 out.endTag(null, TAG_PACKAGE);
396 }
397 }
398 }
399 out.endTag(null, TAG_RANKING);
400 }
401
402 /**
403 * Gets importance.
404 */
405 @Override
406 public int getImportance(String packageName, int uid) {
407 return getOrCreatePackagePreferences(packageName, uid).importance;
408 }
409
410
411 /**
412 * Returns whether the importance of the corresponding notification is user-locked and shouldn't
413 * be adjusted by an assistant (via means of a blocking helper, for example). For the channel
414 * locking field, see {@link NotificationChannel#USER_LOCKED_IMPORTANCE}.
415 */
416 public boolean getIsAppImportanceLocked(String packageName, int uid) {
417 int userLockedFields = getOrCreatePackagePreferences(packageName, uid).lockedAppFields;
418 return (userLockedFields & LockableAppFields.USER_LOCKED_IMPORTANCE) != 0;
419 }
420
421 @Override
422 public boolean canShowBadge(String packageName, int uid) {
423 return getOrCreatePackagePreferences(packageName, uid).showBadge;
424 }
425
426 @Override
427 public void setShowBadge(String packageName, int uid, boolean showBadge) {
428 getOrCreatePackagePreferences(packageName, uid).showBadge = showBadge;
429 updateConfig();
430 }
431
432 @Override
433 public boolean isGroupBlocked(String packageName, int uid, String groupId) {
434 if (groupId == null) {
435 return false;
436 }
437 PackagePreferences r = getOrCreatePackagePreferences(packageName, uid);
438 NotificationChannelGroup group = r.groups.get(groupId);
439 if (group == null) {
440 return false;
441 }
442 return group.isBlocked();
443 }
444
445 int getPackagePriority(String pkg, int uid) {
446 return getOrCreatePackagePreferences(pkg, uid).priority;
447 }
448
449 int getPackageVisibility(String pkg, int uid) {
450 return getOrCreatePackagePreferences(pkg, uid).visibility;
451 }
452
453 @Override
454 public void createNotificationChannelGroup(String pkg, int uid, NotificationChannelGroup group,
455 boolean fromTargetApp) {
456 Preconditions.checkNotNull(pkg);
457 Preconditions.checkNotNull(group);
458 Preconditions.checkNotNull(group.getId());
459 Preconditions.checkNotNull(!TextUtils.isEmpty(group.getName()));
460 PackagePreferences r = getOrCreatePackagePreferences(pkg, uid);
461 if (r == null) {
462 throw new IllegalArgumentException("Invalid package");
463 }
464 final NotificationChannelGroup oldGroup = r.groups.get(group.getId());
465 if (!group.equals(oldGroup)) {
466 // will log for new entries as well as name/description changes
467 MetricsLogger.action(getChannelGroupLog(group.getId(), pkg));
468 }
469 if (oldGroup != null) {
470 group.setChannels(oldGroup.getChannels());
471
472 if (fromTargetApp) {
473 group.setBlocked(oldGroup.isBlocked());
474 }
475 }
476 r.groups.put(group.getId(), group);
477 }
478
479 @Override
480 public void createNotificationChannel(String pkg, int uid, NotificationChannel channel,
481 boolean fromTargetApp, boolean hasDndAccess) {
482 Preconditions.checkNotNull(pkg);
483 Preconditions.checkNotNull(channel);
484 Preconditions.checkNotNull(channel.getId());
485 Preconditions.checkArgument(!TextUtils.isEmpty(channel.getName()));
486 PackagePreferences r = getOrCreatePackagePreferences(pkg, uid);
487 if (r == null) {
488 throw new IllegalArgumentException("Invalid package");
489 }
490 if (channel.getGroup() != null && !r.groups.containsKey(channel.getGroup())) {
491 throw new IllegalArgumentException("NotificationChannelGroup doesn't exist");
492 }
493 if (NotificationChannel.DEFAULT_CHANNEL_ID.equals(channel.getId())) {
494 throw new IllegalArgumentException("Reserved id");
495 }
496 NotificationChannel existing = r.channels.get(channel.getId());
497 // Keep most of the existing settings
498 if (existing != null && fromTargetApp) {
499 if (existing.isDeleted()) {
500 existing.setDeleted(false);
501
502 // log a resurrected channel as if it's new again
503 MetricsLogger.action(getChannelLog(channel, pkg).setType(
504 com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_OPEN));
505 }
506
507 existing.setName(channel.getName().toString());
508 existing.setDescription(channel.getDescription());
509 existing.setBlockableSystem(channel.isBlockableSystem());
510 if (existing.getGroup() == null) {
511 existing.setGroup(channel.getGroup());
512 }
513
514 // Apps are allowed to downgrade channel importance if the user has not changed any
515 // fields on this channel yet.
516 if (existing.getUserLockedFields() == 0 &&
517 channel.getImportance() < existing.getImportance()) {
518 existing.setImportance(channel.getImportance());
519 }
520
521 // system apps and dnd access apps can bypass dnd if the user hasn't changed any
522 // fields on the channel yet
523 if (existing.getUserLockedFields() == 0 && hasDndAccess) {
524 boolean bypassDnd = channel.canBypassDnd();
525 existing.setBypassDnd(bypassDnd);
526
527 if (bypassDnd != mAreChannelsBypassingDnd) {
528 updateChannelsBypassingDnd();
529 }
530 }
531
532 updateConfig();
533 return;
534 }
535 if (channel.getImportance() < IMPORTANCE_NONE
536 || channel.getImportance() > NotificationManager.IMPORTANCE_MAX) {
537 throw new IllegalArgumentException("Invalid importance level");
538 }
539
540 // Reset fields that apps aren't allowed to set.
541 if (fromTargetApp && !hasDndAccess) {
542 channel.setBypassDnd(r.priority == Notification.PRIORITY_MAX);
543 }
544 if (fromTargetApp) {
545 channel.setLockscreenVisibility(r.visibility);
546 }
547 clearLockedFields(channel);
548 if (channel.getLockscreenVisibility() == Notification.VISIBILITY_PUBLIC) {
549 channel.setLockscreenVisibility(
550 NotificationListenerService.Ranking.VISIBILITY_NO_OVERRIDE);
551 }
552 if (!r.showBadge) {
553 channel.setShowBadge(false);
554 }
555
556 r.channels.put(channel.getId(), channel);
557 if (channel.canBypassDnd() != mAreChannelsBypassingDnd) {
558 updateChannelsBypassingDnd();
559 }
560 MetricsLogger.action(getChannelLog(channel, pkg).setType(
561 com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_OPEN));
562 }
563
564 void clearLockedFields(NotificationChannel channel) {
565 channel.unlockFields(channel.getUserLockedFields());
566 }
567
568 @Override
569 public void updateNotificationChannel(String pkg, int uid, NotificationChannel updatedChannel,
570 boolean fromUser) {
571 Preconditions.checkNotNull(updatedChannel);
572 Preconditions.checkNotNull(updatedChannel.getId());
573 PackagePreferences r = getOrCreatePackagePreferences(pkg, uid);
574 if (r == null) {
575 throw new IllegalArgumentException("Invalid package");
576 }
577 NotificationChannel channel = r.channels.get(updatedChannel.getId());
578 if (channel == null || channel.isDeleted()) {
579 throw new IllegalArgumentException("Channel does not exist");
580 }
581 if (updatedChannel.getLockscreenVisibility() == Notification.VISIBILITY_PUBLIC) {
582 updatedChannel.setLockscreenVisibility(
583 NotificationListenerService.Ranking.VISIBILITY_NO_OVERRIDE);
584 }
585 if (!fromUser) {
586 updatedChannel.unlockFields(updatedChannel.getUserLockedFields());
587 }
588 if (fromUser) {
589 updatedChannel.lockFields(channel.getUserLockedFields());
590 lockFieldsForUpdate(channel, updatedChannel);
591 }
592 r.channels.put(updatedChannel.getId(), updatedChannel);
593
594 if (NotificationChannel.DEFAULT_CHANNEL_ID.equals(updatedChannel.getId())) {
595 // copy settings to app level so they are inherited by new channels
596 // when the app migrates
597 r.importance = updatedChannel.getImportance();
598 r.priority = updatedChannel.canBypassDnd()
599 ? Notification.PRIORITY_MAX : Notification.PRIORITY_DEFAULT;
600 r.visibility = updatedChannel.getLockscreenVisibility();
601 r.showBadge = updatedChannel.canShowBadge();
602 }
603
604 if (!channel.equals(updatedChannel)) {
605 // only log if there are real changes
606 MetricsLogger.action(getChannelLog(updatedChannel, pkg));
607 }
608
609 if (updatedChannel.canBypassDnd() != mAreChannelsBypassingDnd) {
610 updateChannelsBypassingDnd();
611 }
612 updateConfig();
613 }
614
615 @Override
616 public NotificationChannel getNotificationChannel(String pkg, int uid, String channelId,
617 boolean includeDeleted) {
618 Preconditions.checkNotNull(pkg);
619 PackagePreferences r = getOrCreatePackagePreferences(pkg, uid);
620 if (r == null) {
621 return null;
622 }
623 if (channelId == null) {
624 channelId = NotificationChannel.DEFAULT_CHANNEL_ID;
625 }
626 final NotificationChannel nc = r.channels.get(channelId);
627 if (nc != null && (includeDeleted || !nc.isDeleted())) {
628 return nc;
629 }
630 return null;
631 }
632
633 @Override
634 public void deleteNotificationChannel(String pkg, int uid, String channelId) {
635 PackagePreferences r = getPackagePreferences(pkg, uid);
636 if (r == null) {
637 return;
638 }
639 NotificationChannel channel = r.channels.get(channelId);
640 if (channel != null) {
641 channel.setDeleted(true);
642 LogMaker lm = getChannelLog(channel, pkg);
643 lm.setType(com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_CLOSE);
644 MetricsLogger.action(lm);
645
646 if (mAreChannelsBypassingDnd && channel.canBypassDnd()) {
647 updateChannelsBypassingDnd();
648 }
649 }
650 }
651
652 @Override
653 @VisibleForTesting
654 public void permanentlyDeleteNotificationChannel(String pkg, int uid, String channelId) {
655 Preconditions.checkNotNull(pkg);
656 Preconditions.checkNotNull(channelId);
657 PackagePreferences r = getPackagePreferences(pkg, uid);
658 if (r == null) {
659 return;
660 }
661 r.channels.remove(channelId);
662 }
663
664 @Override
665 public void permanentlyDeleteNotificationChannels(String pkg, int uid) {
666 Preconditions.checkNotNull(pkg);
667 PackagePreferences r = getPackagePreferences(pkg, uid);
668 if (r == null) {
669 return;
670 }
671 int N = r.channels.size() - 1;
672 for (int i = N; i >= 0; i--) {
673 String key = r.channels.keyAt(i);
674 if (!NotificationChannel.DEFAULT_CHANNEL_ID.equals(key)) {
675 r.channels.remove(key);
676 }
677 }
678 }
679
680 public NotificationChannelGroup getNotificationChannelGroupWithChannels(String pkg,
681 int uid, String groupId, boolean includeDeleted) {
682 Preconditions.checkNotNull(pkg);
683 PackagePreferences r = getPackagePreferences(pkg, uid);
684 if (r == null || groupId == null || !r.groups.containsKey(groupId)) {
685 return null;
686 }
687 NotificationChannelGroup group = r.groups.get(groupId).clone();
688 group.setChannels(new ArrayList<>());
689 int N = r.channels.size();
690 for (int i = 0; i < N; i++) {
691 final NotificationChannel nc = r.channels.valueAt(i);
692 if (includeDeleted || !nc.isDeleted()) {
693 if (groupId.equals(nc.getGroup())) {
694 group.addChannel(nc);
695 }
696 }
697 }
698 return group;
699 }
700
701 public NotificationChannelGroup getNotificationChannelGroup(String groupId, String pkg,
702 int uid) {
703 Preconditions.checkNotNull(pkg);
704 PackagePreferences r = getPackagePreferences(pkg, uid);
705 if (r == null) {
706 return null;
707 }
708 return r.groups.get(groupId);
709 }
710
711 @Override
712 public ParceledListSlice<NotificationChannelGroup> getNotificationChannelGroups(String pkg,
713 int uid, boolean includeDeleted, boolean includeNonGrouped) {
714 Preconditions.checkNotNull(pkg);
715 Map<String, NotificationChannelGroup> groups = new ArrayMap<>();
716 PackagePreferences r = getPackagePreferences(pkg, uid);
717 if (r == null) {
718 return ParceledListSlice.emptyList();
719 }
720 NotificationChannelGroup nonGrouped = new NotificationChannelGroup(null, null);
721 int N = r.channels.size();
722 for (int i = 0; i < N; i++) {
723 final NotificationChannel nc = r.channels.valueAt(i);
724 if (includeDeleted || !nc.isDeleted()) {
725 if (nc.getGroup() != null) {
726 if (r.groups.get(nc.getGroup()) != null) {
727 NotificationChannelGroup ncg = groups.get(nc.getGroup());
728 if (ncg == null) {
729 ncg = r.groups.get(nc.getGroup()).clone();
730 ncg.setChannels(new ArrayList<>());
731 groups.put(nc.getGroup(), ncg);
732
733 }
734 ncg.addChannel(nc);
735 }
736 } else {
737 nonGrouped.addChannel(nc);
738 }
739 }
740 }
741 if (includeNonGrouped && nonGrouped.getChannels().size() > 0) {
742 groups.put(null, nonGrouped);
743 }
744 return new ParceledListSlice<>(new ArrayList<>(groups.values()));
745 }
746
747 public List<NotificationChannel> deleteNotificationChannelGroup(String pkg, int uid,
748 String groupId) {
749 List<NotificationChannel> deletedChannels = new ArrayList<>();
750 PackagePreferences r = getPackagePreferences(pkg, uid);
751 if (r == null || TextUtils.isEmpty(groupId)) {
752 return deletedChannels;
753 }
754
755 r.groups.remove(groupId);
756
757 int N = r.channels.size();
758 for (int i = 0; i < N; i++) {
759 final NotificationChannel nc = r.channels.valueAt(i);
760 if (groupId.equals(nc.getGroup())) {
761 nc.setDeleted(true);
762 deletedChannels.add(nc);
763 }
764 }
765 return deletedChannels;
766 }
767
768 @Override
769 public Collection<NotificationChannelGroup> getNotificationChannelGroups(String pkg,
770 int uid) {
771 PackagePreferences r = getPackagePreferences(pkg, uid);
772 if (r == null) {
773 return new ArrayList<>();
774 }
775 return r.groups.values();
776 }
777
778 @Override
779 public ParceledListSlice<NotificationChannel> getNotificationChannels(String pkg, int uid,
780 boolean includeDeleted) {
781 Preconditions.checkNotNull(pkg);
782 List<NotificationChannel> channels = new ArrayList<>();
783 PackagePreferences r = getPackagePreferences(pkg, uid);
784 if (r == null) {
785 return ParceledListSlice.emptyList();
786 }
787 int N = r.channels.size();
788 for (int i = 0; i < N; i++) {
789 final NotificationChannel nc = r.channels.valueAt(i);
790 if (includeDeleted || !nc.isDeleted()) {
791 channels.add(nc);
792 }
793 }
794 return new ParceledListSlice<>(channels);
795 }
796
797 /**
798 * True for pre-O apps that only have the default channel, or pre O apps that have no
799 * channels yet. This method will create the default channel for pre-O apps that don't have it.
800 * Should never be true for O+ targeting apps, but that's enforced on boot/when an app
801 * upgrades.
802 */
803 public boolean onlyHasDefaultChannel(String pkg, int uid) {
804 PackagePreferences r = getOrCreatePackagePreferences(pkg, uid);
805 if (r.channels.size() == 1
806 && r.channels.containsKey(NotificationChannel.DEFAULT_CHANNEL_ID)) {
807 return true;
808 }
809 return false;
810 }
811
812 public int getDeletedChannelCount(String pkg, int uid) {
813 Preconditions.checkNotNull(pkg);
814 int deletedCount = 0;
815 PackagePreferences r = getPackagePreferences(pkg, uid);
816 if (r == null) {
817 return deletedCount;
818 }
819 int N = r.channels.size();
820 for (int i = 0; i < N; i++) {
821 final NotificationChannel nc = r.channels.valueAt(i);
822 if (nc.isDeleted()) {
823 deletedCount++;
824 }
825 }
826 return deletedCount;
827 }
828
829 public int getBlockedChannelCount(String pkg, int uid) {
830 Preconditions.checkNotNull(pkg);
831 int blockedCount = 0;
832 PackagePreferences r = getPackagePreferences(pkg, uid);
833 if (r == null) {
834 return blockedCount;
835 }
836 int N = r.channels.size();
837 for (int i = 0; i < N; i++) {
838 final NotificationChannel nc = r.channels.valueAt(i);
839 if (!nc.isDeleted() && IMPORTANCE_NONE == nc.getImportance()) {
840 blockedCount++;
841 }
842 }
843 return blockedCount;
844 }
845
846 public int getBlockedAppCount(int userId) {
847 int count = 0;
848 synchronized (mPackagePreferencess) {
849 final int N = mPackagePreferencess.size();
850 for (int i = 0; i < N; i++) {
851 final PackagePreferences r = mPackagePreferencess.valueAt(i);
852 if (userId == UserHandle.getUserId(r.uid)
853 && r.importance == IMPORTANCE_NONE) {
854 count++;
855 }
856 }
857 }
858 return count;
859 }
860
861 public void updateChannelsBypassingDnd() {
862 synchronized (mPackagePreferencess) {
863 final int numPackagePreferencess = mPackagePreferencess.size();
864 for (int PackagePreferencesIndex = 0; PackagePreferencesIndex < numPackagePreferencess;
865 PackagePreferencesIndex++) {
866 final PackagePreferences r = mPackagePreferencess.valueAt(PackagePreferencesIndex);
867 final int numChannels = r.channels.size();
868
869 for (int channelIndex = 0; channelIndex < numChannels; channelIndex++) {
870 NotificationChannel channel = r.channels.valueAt(channelIndex);
871 if (!channel.isDeleted() && channel.canBypassDnd()) {
872 // If any channel bypasses DND, synchronize state and return early.
873 if (!mAreChannelsBypassingDnd) {
874 mAreChannelsBypassingDnd = true;
875 updateZenPolicy(true);
876 }
877 return;
878 }
879 }
880 }
881 }
882
883 // If no channels bypass DND, update the zen policy once to disable DND bypass.
884 if (mAreChannelsBypassingDnd) {
885 mAreChannelsBypassingDnd = false;
886 updateZenPolicy(false);
887 }
888 }
889
890 public void updateZenPolicy(boolean areChannelsBypassingDnd) {
891 NotificationManager.Policy policy = mZenModeHelper.getNotificationPolicy();
892 mZenModeHelper.setNotificationPolicy(new NotificationManager.Policy(
893 policy.priorityCategories, policy.priorityCallSenders,
894 policy.priorityMessageSenders, policy.suppressedVisualEffects,
895 (areChannelsBypassingDnd ? NotificationManager.Policy.STATE_CHANNELS_BYPASSING_DND
896 : 0)));
897 }
898
899 public boolean areChannelsBypassingDnd() {
900 return mAreChannelsBypassingDnd;
901 }
902
903 /**
904 * Sets importance.
905 */
906 @Override
907 public void setImportance(String pkgName, int uid, int importance) {
908 getOrCreatePackagePreferences(pkgName, uid).importance = importance;
909 updateConfig();
910 }
911
912 public void setEnabled(String packageName, int uid, boolean enabled) {
913 boolean wasEnabled = getImportance(packageName, uid) != IMPORTANCE_NONE;
914 if (wasEnabled == enabled) {
915 return;
916 }
917 setImportance(packageName, uid,
918 enabled ? DEFAULT_IMPORTANCE : IMPORTANCE_NONE);
919 }
920
921 /**
922 * Sets whether any notifications from the app, represented by the given {@code pkgName} and
923 * {@code uid}, have their importance locked by the user. Locked notifications don't get
924 * considered for sentiment adjustments (and thus never show a blocking helper).
925 */
926 public void setAppImportanceLocked(String packageName, int uid) {
927 PackagePreferences PackagePreferences = getOrCreatePackagePreferences(packageName, uid);
928 if ((PackagePreferences.lockedAppFields & LockableAppFields.USER_LOCKED_IMPORTANCE) != 0) {
929 return;
930 }
931
932 PackagePreferences.lockedAppFields =
933 PackagePreferences.lockedAppFields | LockableAppFields.USER_LOCKED_IMPORTANCE;
934 updateConfig();
935 }
936
937 @VisibleForTesting
938 void lockFieldsForUpdate(NotificationChannel original, NotificationChannel update) {
939 if (original.canBypassDnd() != update.canBypassDnd()) {
940 update.lockFields(NotificationChannel.USER_LOCKED_PRIORITY);
941 }
942 if (original.getLockscreenVisibility() != update.getLockscreenVisibility()) {
943 update.lockFields(NotificationChannel.USER_LOCKED_VISIBILITY);
944 }
945 if (original.getImportance() != update.getImportance()) {
946 update.lockFields(NotificationChannel.USER_LOCKED_IMPORTANCE);
947 }
948 if (original.shouldShowLights() != update.shouldShowLights()
949 || original.getLightColor() != update.getLightColor()) {
950 update.lockFields(NotificationChannel.USER_LOCKED_LIGHTS);
951 }
952 if (!Objects.equals(original.getSound(), update.getSound())) {
953 update.lockFields(NotificationChannel.USER_LOCKED_SOUND);
954 }
955 if (!Arrays.equals(original.getVibrationPattern(), update.getVibrationPattern())
956 || original.shouldVibrate() != update.shouldVibrate()) {
957 update.lockFields(NotificationChannel.USER_LOCKED_VIBRATION);
958 }
959 if (original.canShowBadge() != update.canShowBadge()) {
960 update.lockFields(NotificationChannel.USER_LOCKED_SHOW_BADGE);
961 }
962 }
963
964 public void dump(PrintWriter pw, String prefix,
965 @NonNull NotificationManagerService.DumpFilter filter) {
966 pw.print(prefix);
967 pw.println("per-package config:");
968
969 pw.println("PackagePreferencess:");
970 synchronized (mPackagePreferencess) {
971 dumpPackagePreferencess(pw, prefix, filter, mPackagePreferencess);
972 }
973 pw.println("Restored without uid:");
974 dumpPackagePreferencess(pw, prefix, filter, mRestoredWithoutUids);
975 }
976
977 public void dump(ProtoOutputStream proto,
978 @NonNull NotificationManagerService.DumpFilter filter) {
979 synchronized (mPackagePreferencess) {
980 dumpPackagePreferencess(proto, RankingHelperProto.RECORDS, filter,
981 mPackagePreferencess);
982 }
983 dumpPackagePreferencess(proto, RankingHelperProto.RECORDS_RESTORED_WITHOUT_UID, filter,
984 mRestoredWithoutUids);
985 }
986
987 private static void dumpPackagePreferencess(PrintWriter pw, String prefix,
988 @NonNull NotificationManagerService.DumpFilter filter,
989 ArrayMap<String, PackagePreferences> PackagePreferencess) {
990 final int N = PackagePreferencess.size();
991 for (int i = 0; i < N; i++) {
992 final PackagePreferences r = PackagePreferencess.valueAt(i);
993 if (filter.matches(r.pkg)) {
994 pw.print(prefix);
995 pw.print(" AppSettings: ");
996 pw.print(r.pkg);
997 pw.print(" (");
998 pw.print(r.uid == PackagePreferences.UNKNOWN_UID ? "UNKNOWN_UID"
999 : Integer.toString(r.uid));
1000 pw.print(')');
1001 if (r.importance != DEFAULT_IMPORTANCE) {
1002 pw.print(" importance=");
1003 pw.print(NotificationListenerService.Ranking.importanceToString(r.importance));
1004 }
1005 if (r.priority != DEFAULT_PRIORITY) {
1006 pw.print(" priority=");
1007 pw.print(Notification.priorityToString(r.priority));
1008 }
1009 if (r.visibility != DEFAULT_VISIBILITY) {
1010 pw.print(" visibility=");
1011 pw.print(Notification.visibilityToString(r.visibility));
1012 }
1013 pw.print(" showBadge=");
1014 pw.print(Boolean.toString(r.showBadge));
1015 pw.println();
1016 for (NotificationChannel channel : r.channels.values()) {
1017 pw.print(prefix);
1018 channel.dump(pw, " ", filter.redact);
1019 }
1020 for (NotificationChannelGroup group : r.groups.values()) {
1021 pw.print(prefix);
1022 pw.print(" ");
1023 pw.print(" ");
1024 pw.println(group);
1025 }
1026 }
1027 }
1028 }
1029
1030 private static void dumpPackagePreferencess(ProtoOutputStream proto, long fieldId,
1031 @NonNull NotificationManagerService.DumpFilter filter,
1032 ArrayMap<String, PackagePreferences> PackagePreferencess) {
1033 final int N = PackagePreferencess.size();
1034 long fToken;
1035 for (int i = 0; i < N; i++) {
1036 final PackagePreferences r = PackagePreferencess.valueAt(i);
1037 if (filter.matches(r.pkg)) {
1038 fToken = proto.start(fieldId);
1039
1040 proto.write(RankingHelperProto.RecordProto.PACKAGE, r.pkg);
1041 proto.write(RankingHelperProto.RecordProto.UID, r.uid);
1042 proto.write(RankingHelperProto.RecordProto.IMPORTANCE, r.importance);
1043 proto.write(RankingHelperProto.RecordProto.PRIORITY, r.priority);
1044 proto.write(RankingHelperProto.RecordProto.VISIBILITY, r.visibility);
1045 proto.write(RankingHelperProto.RecordProto.SHOW_BADGE, r.showBadge);
1046
1047 for (NotificationChannel channel : r.channels.values()) {
1048 channel.writeToProto(proto, RankingHelperProto.RecordProto.CHANNELS);
1049 }
1050 for (NotificationChannelGroup group : r.groups.values()) {
1051 group.writeToProto(proto, RankingHelperProto.RecordProto.CHANNEL_GROUPS);
1052 }
1053
1054 proto.end(fToken);
1055 }
1056 }
1057 }
1058
1059 public JSONObject dumpJson(NotificationManagerService.DumpFilter filter) {
1060 JSONObject ranking = new JSONObject();
1061 JSONArray PackagePreferencess = new JSONArray();
1062 try {
1063 ranking.put("noUid", mRestoredWithoutUids.size());
1064 } catch (JSONException e) {
1065 // pass
1066 }
1067 synchronized (mPackagePreferencess) {
1068 final int N = mPackagePreferencess.size();
1069 for (int i = 0; i < N; i++) {
1070 final PackagePreferences r = mPackagePreferencess.valueAt(i);
1071 if (filter == null || filter.matches(r.pkg)) {
1072 JSONObject PackagePreferences = new JSONObject();
1073 try {
1074 PackagePreferences.put("userId", UserHandle.getUserId(r.uid));
1075 PackagePreferences.put("packageName", r.pkg);
1076 if (r.importance != DEFAULT_IMPORTANCE) {
1077 PackagePreferences.put("importance",
1078 NotificationListenerService.Ranking.importanceToString(
1079 r.importance));
1080 }
1081 if (r.priority != DEFAULT_PRIORITY) {
1082 PackagePreferences.put("priority",
1083 Notification.priorityToString(r.priority));
1084 }
1085 if (r.visibility != DEFAULT_VISIBILITY) {
1086 PackagePreferences.put("visibility",
1087 Notification.visibilityToString(r.visibility));
1088 }
1089 if (r.showBadge != DEFAULT_SHOW_BADGE) {
1090 PackagePreferences.put("showBadge", Boolean.valueOf(r.showBadge));
1091 }
1092 JSONArray channels = new JSONArray();
1093 for (NotificationChannel channel : r.channels.values()) {
1094 channels.put(channel.toJson());
1095 }
1096 PackagePreferences.put("channels", channels);
1097 JSONArray groups = new JSONArray();
1098 for (NotificationChannelGroup group : r.groups.values()) {
1099 groups.put(group.toJson());
1100 }
1101 PackagePreferences.put("groups", groups);
1102 } catch (JSONException e) {
1103 // pass
1104 }
1105 PackagePreferencess.put(PackagePreferences);
1106 }
1107 }
1108 }
1109 try {
1110 ranking.put("PackagePreferencess", PackagePreferencess);
1111 } catch (JSONException e) {
1112 // pass
1113 }
1114 return ranking;
1115 }
1116
1117 /**
1118 * Dump only the ban information as structured JSON for the stats collector.
1119 *
1120 * This is intentionally redundant with {#link dumpJson} because the old
1121 * scraper will expect this format.
1122 *
1123 * @param filter
1124 * @return
1125 */
1126 public JSONArray dumpBansJson(NotificationManagerService.DumpFilter filter) {
1127 JSONArray bans = new JSONArray();
1128 Map<Integer, String> packageBans = getPackageBans();
1129 for (Map.Entry<Integer, String> ban : packageBans.entrySet()) {
1130 final int userId = UserHandle.getUserId(ban.getKey());
1131 final String packageName = ban.getValue();
1132 if (filter == null || filter.matches(packageName)) {
1133 JSONObject banJson = new JSONObject();
1134 try {
1135 banJson.put("userId", userId);
1136 banJson.put("packageName", packageName);
1137 } catch (JSONException e) {
1138 e.printStackTrace();
1139 }
1140 bans.put(banJson);
1141 }
1142 }
1143 return bans;
1144 }
1145
1146 public Map<Integer, String> getPackageBans() {
1147 synchronized (mPackagePreferencess) {
1148 final int N = mPackagePreferencess.size();
1149 ArrayMap<Integer, String> packageBans = new ArrayMap<>(N);
1150 for (int i = 0; i < N; i++) {
1151 final PackagePreferences r = mPackagePreferencess.valueAt(i);
1152 if (r.importance == IMPORTANCE_NONE) {
1153 packageBans.put(r.uid, r.pkg);
1154 }
1155 }
1156
1157 return packageBans;
1158 }
1159 }
1160
1161 /**
1162 * Dump only the channel information as structured JSON for the stats collector.
1163 *
1164 * This is intentionally redundant with {#link dumpJson} because the old
1165 * scraper will expect this format.
1166 *
1167 * @param filter
1168 * @return
1169 */
1170 public JSONArray dumpChannelsJson(NotificationManagerService.DumpFilter filter) {
1171 JSONArray channels = new JSONArray();
1172 Map<String, Integer> packageChannels = getPackageChannels();
1173 for (Map.Entry<String, Integer> channelCount : packageChannels.entrySet()) {
1174 final String packageName = channelCount.getKey();
1175 if (filter == null || filter.matches(packageName)) {
1176 JSONObject channelCountJson = new JSONObject();
1177 try {
1178 channelCountJson.put("packageName", packageName);
1179 channelCountJson.put("channelCount", channelCount.getValue());
1180 } catch (JSONException e) {
1181 e.printStackTrace();
1182 }
1183 channels.put(channelCountJson);
1184 }
1185 }
1186 return channels;
1187 }
1188
1189 private Map<String, Integer> getPackageChannels() {
1190 ArrayMap<String, Integer> packageChannels = new ArrayMap<>();
1191 synchronized (mPackagePreferencess) {
1192 for (int i = 0; i < mPackagePreferencess.size(); i++) {
1193 final PackagePreferences r = mPackagePreferencess.valueAt(i);
1194 int channelCount = 0;
1195 for (int j = 0; j < r.channels.size(); j++) {
1196 if (!r.channels.valueAt(j).isDeleted()) {
1197 channelCount++;
1198 }
1199 }
1200 packageChannels.put(r.pkg, channelCount);
1201 }
1202 }
1203 return packageChannels;
1204 }
1205
1206 public void onUserRemoved(int userId) {
1207 synchronized (mPackagePreferencess) {
1208 int N = mPackagePreferencess.size();
1209 for (int i = N - 1; i >= 0; i--) {
1210 PackagePreferences PackagePreferences = mPackagePreferencess.valueAt(i);
1211 if (UserHandle.getUserId(PackagePreferences.uid) == userId) {
1212 mPackagePreferencess.removeAt(i);
1213 }
1214 }
1215 }
1216 }
1217
1218 protected void onLocaleChanged(Context context, int userId) {
1219 synchronized (mPackagePreferencess) {
1220 int N = mPackagePreferencess.size();
1221 for (int i = 0; i < N; i++) {
1222 PackagePreferences PackagePreferences = mPackagePreferencess.valueAt(i);
1223 if (UserHandle.getUserId(PackagePreferences.uid) == userId) {
1224 if (PackagePreferences.channels.containsKey(
1225 NotificationChannel.DEFAULT_CHANNEL_ID)) {
1226 PackagePreferences.channels.get(
1227 NotificationChannel.DEFAULT_CHANNEL_ID).setName(
1228 context.getResources().getString(
1229 R.string.default_notification_channel_label));
1230 }
1231 }
1232 }
1233 }
1234 }
1235
1236 public void onPackagesChanged(boolean removingPackage, int changeUserId, String[] pkgList,
1237 int[] uidList) {
1238 if (pkgList == null || pkgList.length == 0) {
1239 return; // nothing to do
1240 }
1241 boolean updated = false;
1242 if (removingPackage) {
1243 // Remove notification settings for uninstalled package
1244 int size = Math.min(pkgList.length, uidList.length);
1245 for (int i = 0; i < size; i++) {
1246 final String pkg = pkgList[i];
1247 final int uid = uidList[i];
1248 synchronized (mPackagePreferencess) {
1249 mPackagePreferencess.remove(packagePreferencesKey(pkg, uid));
1250 }
1251 mRestoredWithoutUids.remove(pkg);
1252 updated = true;
1253 }
1254 } else {
1255 for (String pkg : pkgList) {
1256 // Package install
1257 final PackagePreferences r = mRestoredWithoutUids.get(pkg);
1258 if (r != null) {
1259 try {
1260 r.uid = mPm.getPackageUidAsUser(r.pkg, changeUserId);
1261 mRestoredWithoutUids.remove(pkg);
1262 synchronized (mPackagePreferencess) {
1263 mPackagePreferencess.put(packagePreferencesKey(r.pkg, r.uid), r);
1264 }
1265 updated = true;
1266 } catch (PackageManager.NameNotFoundException e) {
1267 // noop
1268 }
1269 }
1270 // Package upgrade
1271 try {
1272 PackagePreferences fullPackagePreferences = getPackagePreferences(pkg,
1273 mPm.getPackageUidAsUser(pkg, changeUserId));
1274 if (fullPackagePreferences != null) {
1275 createDefaultChannelIfNeeded(fullPackagePreferences);
1276 deleteDefaultChannelIfNeeded(fullPackagePreferences);
1277 }
1278 } catch (PackageManager.NameNotFoundException e) {
1279 }
1280 }
1281 }
1282
1283 if (updated) {
1284 updateConfig();
1285 }
1286 }
1287
1288 private LogMaker getChannelLog(NotificationChannel channel, String pkg) {
1289 return new LogMaker(
1290 com.android.internal.logging.nano.MetricsProto.MetricsEvent
1291 .ACTION_NOTIFICATION_CHANNEL)
1292 .setType(com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_UPDATE)
1293 .setPackageName(pkg)
1294 .addTaggedData(
1295 com.android.internal.logging.nano.MetricsProto.MetricsEvent
1296 .FIELD_NOTIFICATION_CHANNEL_ID,
1297 channel.getId())
1298 .addTaggedData(
1299 com.android.internal.logging.nano.MetricsProto.MetricsEvent
1300 .FIELD_NOTIFICATION_CHANNEL_IMPORTANCE,
1301 channel.getImportance());
1302 }
1303
1304 private LogMaker getChannelGroupLog(String groupId, String pkg) {
1305 return new LogMaker(
1306 com.android.internal.logging.nano.MetricsProto.MetricsEvent
1307 .ACTION_NOTIFICATION_CHANNEL_GROUP)
1308 .setType(com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_UPDATE)
1309 .addTaggedData(
1310 com.android.internal.logging.nano.MetricsProto.MetricsEvent
1311 .FIELD_NOTIFICATION_CHANNEL_GROUP_ID,
1312 groupId)
1313 .setPackageName(pkg);
1314 }
1315
1316
1317 public void updateBadgingEnabled() {
1318 if (mBadgingEnabled == null) {
1319 mBadgingEnabled = new SparseBooleanArray();
1320 }
1321 boolean changed = false;
1322 // update the cached values
1323 for (int index = 0; index < mBadgingEnabled.size(); index++) {
1324 int userId = mBadgingEnabled.keyAt(index);
1325 final boolean oldValue = mBadgingEnabled.get(userId);
1326 final boolean newValue = Settings.Secure.getIntForUser(mContext.getContentResolver(),
1327 Settings.Secure.NOTIFICATION_BADGING,
1328 DEFAULT_SHOW_BADGE ? 1 : 0, userId) != 0;
1329 mBadgingEnabled.put(userId, newValue);
1330 changed |= oldValue != newValue;
1331 }
1332 if (changed) {
1333 updateConfig();
1334 }
1335 }
1336
1337 public boolean badgingEnabled(UserHandle userHandle) {
1338 int userId = userHandle.getIdentifier();
1339 if (userId == UserHandle.USER_ALL) {
1340 return false;
1341 }
1342 if (mBadgingEnabled.indexOfKey(userId) < 0) {
1343 mBadgingEnabled.put(userId,
1344 Settings.Secure.getIntForUser(mContext.getContentResolver(),
1345 Settings.Secure.NOTIFICATION_BADGING,
1346 DEFAULT_SHOW_BADGE ? 1 : 0, userId) != 0);
1347 }
1348 return mBadgingEnabled.get(userId, DEFAULT_SHOW_BADGE);
1349 }
1350
1351 private void updateConfig() {
1352 mRankingHandler.requestSort();
1353 }
1354
1355 private static String packagePreferencesKey(String pkg, int uid) {
1356 return pkg + "|" + uid;
1357 }
1358
1359 private static class PackagePreferences {
1360 static int UNKNOWN_UID = UserHandle.USER_NULL;
1361
1362 String pkg;
1363 int uid = UNKNOWN_UID;
1364 int importance = DEFAULT_IMPORTANCE;
1365 int priority = DEFAULT_PRIORITY;
1366 int visibility = DEFAULT_VISIBILITY;
1367 boolean showBadge = DEFAULT_SHOW_BADGE;
1368 int lockedAppFields = DEFAULT_LOCKED_APP_FIELDS;
1369
1370 ArrayMap<String, NotificationChannel> channels = new ArrayMap<>();
1371 Map<String, NotificationChannelGroup> groups = new ConcurrentHashMap<>();
1372 }
1373}