ZenModeHelper.java revision 29b7872bf454d61f849d32d4a7a50485aa9c282d
1/** 2 * Copyright (c) 2014, 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.media.AudioAttributes.USAGE_ALARM; 20import static android.media.AudioAttributes.USAGE_NOTIFICATION; 21import static android.media.AudioAttributes.USAGE_NOTIFICATION_RINGTONE; 22 23import android.app.AppOpsManager; 24import android.app.Notification; 25import android.content.ComponentName; 26import android.content.ContentResolver; 27import android.content.Context; 28import android.content.res.Resources; 29import android.content.res.XmlResourceParser; 30import android.database.ContentObserver; 31import android.media.AudioAttributes; 32import android.media.AudioManager; 33import android.media.AudioManagerInternal; 34import android.net.Uri; 35import android.os.Bundle; 36import android.os.Handler; 37import android.os.Looper; 38import android.os.Message; 39import android.os.UserHandle; 40import android.provider.Settings.Global; 41import android.provider.Settings.Secure; 42import android.service.notification.NotificationListenerService; 43import android.service.notification.ZenModeConfig; 44import android.telecom.TelecomManager; 45import android.util.Log; 46import android.util.Slog; 47 48import com.android.internal.R; 49import com.android.server.LocalServices; 50 51import libcore.io.IoUtils; 52 53import org.xmlpull.v1.XmlPullParser; 54import org.xmlpull.v1.XmlPullParserException; 55import org.xmlpull.v1.XmlSerializer; 56 57import java.io.IOException; 58import java.io.PrintWriter; 59import java.util.ArrayList; 60import java.util.Objects; 61 62/** 63 * NotificationManagerService helper for functionality related to zen mode. 64 */ 65public class ZenModeHelper implements AudioManagerInternal.RingerModeDelegate { 66 private static final String TAG = "ZenModeHelper"; 67 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG); 68 69 private final Context mContext; 70 private final H mHandler; 71 private final SettingsObserver mSettingsObserver; 72 private final AppOpsManager mAppOps; 73 private final ZenModeConfig mDefaultConfig; 74 private final ArrayList<Callback> mCallbacks = new ArrayList<Callback>(); 75 76 private ComponentName mDefaultPhoneApp; 77 private int mZenMode; 78 private ZenModeConfig mConfig; 79 private AudioManagerInternal mAudioManager; 80 private int mPreviousRingerMode = -1; 81 private boolean mEffectsSuppressed; 82 83 public ZenModeHelper(Context context, Looper looper) { 84 mContext = context; 85 mHandler = new H(looper); 86 mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); 87 mDefaultConfig = readDefaultConfig(context.getResources()); 88 mConfig = mDefaultConfig; 89 mSettingsObserver = new SettingsObserver(mHandler); 90 mSettingsObserver.observe(); 91 } 92 93 public static ZenModeConfig readDefaultConfig(Resources resources) { 94 XmlResourceParser parser = null; 95 try { 96 parser = resources.getXml(R.xml.default_zen_mode_config); 97 while (parser.next() != XmlPullParser.END_DOCUMENT) { 98 final ZenModeConfig config = ZenModeConfig.readXml(parser); 99 if (config != null) return config; 100 } 101 } catch (Exception e) { 102 Slog.w(TAG, "Error reading default zen mode config from resource", e); 103 } finally { 104 IoUtils.closeQuietly(parser); 105 } 106 return new ZenModeConfig(); 107 } 108 109 public void addCallback(Callback callback) { 110 mCallbacks.add(callback); 111 } 112 113 public void removeCallback(Callback callback) { 114 mCallbacks.remove(callback); 115 } 116 117 public void onSystemReady() { 118 mAudioManager = LocalServices.getService(AudioManagerInternal.class); 119 if (mAudioManager != null) { 120 mAudioManager.setRingerModeDelegate(this); 121 } 122 } 123 124 public int getZenModeListenerInterruptionFilter() { 125 switch (mZenMode) { 126 case Global.ZEN_MODE_OFF: 127 return NotificationListenerService.INTERRUPTION_FILTER_ALL; 128 case Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS: 129 return NotificationListenerService.INTERRUPTION_FILTER_PRIORITY; 130 case Global.ZEN_MODE_NO_INTERRUPTIONS: 131 return NotificationListenerService.INTERRUPTION_FILTER_NONE; 132 default: 133 return 0; 134 } 135 } 136 137 private static int zenModeFromListenerInterruptionFilter(int listenerInterruptionFilter, 138 int defValue) { 139 switch (listenerInterruptionFilter) { 140 case NotificationListenerService.INTERRUPTION_FILTER_ALL: 141 return Global.ZEN_MODE_OFF; 142 case NotificationListenerService.INTERRUPTION_FILTER_PRIORITY: 143 return Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS; 144 case NotificationListenerService.INTERRUPTION_FILTER_NONE: 145 return Global.ZEN_MODE_NO_INTERRUPTIONS; 146 default: 147 return defValue; 148 } 149 } 150 151 public void requestFromListener(ComponentName name, int interruptionFilter) { 152 final int newZen = zenModeFromListenerInterruptionFilter(interruptionFilter, -1); 153 if (newZen != -1) { 154 setZenMode(newZen, "listener:" + (name != null ? name.flattenToShortString() : null)); 155 } 156 } 157 158 public void setEffectsSuppressed(boolean effectsSuppressed) { 159 if (mEffectsSuppressed == effectsSuppressed) return; 160 mEffectsSuppressed = effectsSuppressed; 161 applyRestrictions(); 162 } 163 164 public boolean shouldIntercept(NotificationRecord record) { 165 if (isSystem(record)) { 166 return false; 167 } 168 switch (mZenMode) { 169 case Global.ZEN_MODE_NO_INTERRUPTIONS: 170 // #notevenalarms 171 ZenLog.traceIntercepted(record, "none"); 172 return true; 173 case Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS: 174 if (isAlarm(record)) { 175 // Alarms are always priority 176 return false; 177 } 178 // allow user-prioritized packages through in priority mode 179 if (record.getPackagePriority() == Notification.PRIORITY_MAX) { 180 ZenLog.traceNotIntercepted(record, "priorityApp"); 181 return false; 182 } 183 if (isCall(record)) { 184 if (!mConfig.allowCalls) { 185 ZenLog.traceIntercepted(record, "!allowCalls"); 186 return true; 187 } 188 return shouldInterceptAudience(record); 189 } 190 if (isMessage(record)) { 191 if (!mConfig.allowMessages) { 192 ZenLog.traceIntercepted(record, "!allowMessages"); 193 return true; 194 } 195 return shouldInterceptAudience(record); 196 } 197 if (isEvent(record)) { 198 if (!mConfig.allowEvents) { 199 ZenLog.traceIntercepted(record, "!allowEvents"); 200 return true; 201 } 202 return false; 203 } 204 ZenLog.traceIntercepted(record, "!priority"); 205 return true; 206 default: 207 return false; 208 } 209 } 210 211 private boolean shouldInterceptAudience(NotificationRecord record) { 212 if (!audienceMatches(record.getContactAffinity())) { 213 ZenLog.traceIntercepted(record, "!audienceMatches"); 214 return true; 215 } 216 return false; 217 } 218 219 public int getZenMode() { 220 return mZenMode; 221 } 222 223 public void setZenMode(int zenMode, String reason) { 224 ZenLog.traceSetZenMode(zenMode, reason); 225 Global.putInt(mContext.getContentResolver(), Global.ZEN_MODE, zenMode); 226 } 227 228 public void updateZenMode() { 229 final int oldMode = mZenMode; 230 final int newMode = Global.getInt(mContext.getContentResolver(), 231 Global.ZEN_MODE, Global.ZEN_MODE_OFF); 232 if (oldMode != newMode) { 233 ZenLog.traceUpdateZenMode(oldMode, newMode); 234 } 235 mZenMode = newMode; 236 applyRestrictions(); 237 onZenUpdated(oldMode, newMode); 238 dispatchOnZenModeChanged(); 239 } 240 241 private void applyRestrictions() { 242 final boolean zen = mZenMode != Global.ZEN_MODE_OFF; 243 244 // notification restrictions 245 final boolean muteNotifications = mEffectsSuppressed; 246 applyRestrictions(muteNotifications, USAGE_NOTIFICATION); 247 248 // call restrictions 249 final boolean muteCalls = zen && !mConfig.allowCalls || mEffectsSuppressed; 250 applyRestrictions(muteCalls, USAGE_NOTIFICATION_RINGTONE); 251 252 // alarm restrictions 253 final boolean muteAlarms = mZenMode == Global.ZEN_MODE_NO_INTERRUPTIONS; 254 applyRestrictions(muteAlarms, USAGE_ALARM); 255 } 256 257 private void applyRestrictions(boolean mute, int usage) { 258 final String[] exceptionPackages = null; // none (for now) 259 mAppOps.setRestriction(AppOpsManager.OP_VIBRATE, usage, 260 mute ? AppOpsManager.MODE_IGNORED : AppOpsManager.MODE_ALLOWED, 261 exceptionPackages); 262 mAppOps.setRestriction(AppOpsManager.OP_PLAY_AUDIO, usage, 263 mute ? AppOpsManager.MODE_IGNORED : AppOpsManager.MODE_ALLOWED, 264 exceptionPackages); 265 } 266 267 public void dump(PrintWriter pw, String prefix) { 268 pw.print(prefix); pw.print("mZenMode="); 269 pw.println(Global.zenModeToString(mZenMode)); 270 pw.print(prefix); pw.print("mConfig="); pw.println(mConfig); 271 pw.print(prefix); pw.print("mDefaultConfig="); pw.println(mDefaultConfig); 272 pw.print(prefix); pw.print("mPreviousRingerMode="); pw.println(mPreviousRingerMode); 273 pw.print(prefix); pw.print("mDefaultPhoneApp="); pw.println(mDefaultPhoneApp); 274 pw.print(prefix); pw.print("mEffectsSuppressed="); pw.println(mEffectsSuppressed); 275 } 276 277 public void readXml(XmlPullParser parser) throws XmlPullParserException, IOException { 278 final ZenModeConfig config = ZenModeConfig.readXml(parser); 279 if (config != null) { 280 setConfig(config); 281 } 282 } 283 284 public void writeXml(XmlSerializer out) throws IOException { 285 mConfig.writeXml(out); 286 } 287 288 public ZenModeConfig getConfig() { 289 return mConfig; 290 } 291 292 public boolean setConfig(ZenModeConfig config) { 293 if (config == null || !config.isValid()) return false; 294 if (config.equals(mConfig)) return true; 295 ZenLog.traceConfig(mConfig, config); 296 mConfig = config; 297 dispatchOnConfigChanged(); 298 final String val = Integer.toString(mConfig.hashCode()); 299 Global.putString(mContext.getContentResolver(), Global.ZEN_MODE_CONFIG_ETAG, val); 300 updateZenMode(); 301 return true; 302 } 303 304 private void onZenUpdated(int oldZen, int newZen) { 305 if (mAudioManager == null) return; 306 if (oldZen == newZen) return; 307 308 // force the ringer mode into compliance 309 final int ringerModeInternal = mAudioManager.getRingerModeInternal(); 310 int newRingerModeInternal = ringerModeInternal; 311 switch (newZen) { 312 case Global.ZEN_MODE_NO_INTERRUPTIONS: 313 if (ringerModeInternal != AudioManager.RINGER_MODE_SILENT) { 314 mPreviousRingerMode = ringerModeInternal; 315 newRingerModeInternal = AudioManager.RINGER_MODE_SILENT; 316 } 317 break; 318 case Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS: 319 case Global.ZEN_MODE_OFF: 320 if (ringerModeInternal == AudioManager.RINGER_MODE_SILENT) { 321 newRingerModeInternal = mPreviousRingerMode != -1 ? mPreviousRingerMode 322 : AudioManager.RINGER_MODE_NORMAL; 323 mPreviousRingerMode = -1; 324 } 325 break; 326 } 327 if (newRingerModeInternal != -1) { 328 mAudioManager.setRingerModeInternal(newRingerModeInternal, TAG); 329 } 330 } 331 332 @Override // RingerModeDelegate 333 public int onSetRingerModeInternal(int ringerModeOld, int ringerModeNew, String caller, 334 int ringerModeExternal) { 335 final boolean isChange = ringerModeOld != ringerModeNew; 336 337 int ringerModeExternalOut = ringerModeNew; 338 339 int newZen = -1; 340 switch(ringerModeNew) { 341 case AudioManager.RINGER_MODE_SILENT: 342 if (isChange) { 343 if (mZenMode != Global.ZEN_MODE_NO_INTERRUPTIONS) { 344 newZen = Global.ZEN_MODE_NO_INTERRUPTIONS; 345 } 346 } 347 break; 348 case AudioManager.RINGER_MODE_VIBRATE: 349 case AudioManager.RINGER_MODE_NORMAL: 350 if (isChange && ringerModeOld == AudioManager.RINGER_MODE_SILENT 351 && mZenMode == Global.ZEN_MODE_NO_INTERRUPTIONS) { 352 newZen = Global.ZEN_MODE_OFF; 353 } else if (mZenMode != Global.ZEN_MODE_OFF) { 354 ringerModeExternalOut = AudioManager.RINGER_MODE_SILENT; 355 } 356 break; 357 } 358 if (newZen != -1) { 359 mHandler.postSetZenMode(newZen, "ringerModeInternal"); 360 } 361 362 if (isChange || newZen != -1 || ringerModeExternal != ringerModeExternalOut) { 363 ZenLog.traceSetRingerModeInternal(ringerModeOld, ringerModeNew, caller, 364 ringerModeExternal, ringerModeExternalOut); 365 } 366 return ringerModeExternalOut; 367 } 368 369 @Override // RingerModeDelegate 370 public int onSetRingerModeExternal(int ringerModeOld, int ringerModeNew, String caller, 371 int ringerModeInternal) { 372 int ringerModeInternalOut = ringerModeNew; 373 final boolean isChange = ringerModeOld != ringerModeNew; 374 final boolean isVibrate = ringerModeInternal == AudioManager.RINGER_MODE_VIBRATE; 375 376 int newZen = -1; 377 switch(ringerModeNew) { 378 case AudioManager.RINGER_MODE_SILENT: 379 if (isChange) { 380 if (mZenMode == Global.ZEN_MODE_OFF) { 381 newZen = Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS; 382 } 383 ringerModeInternalOut = isVibrate ? AudioManager.RINGER_MODE_VIBRATE 384 : AudioManager.RINGER_MODE_NORMAL; 385 } else { 386 ringerModeInternalOut = ringerModeInternal; 387 } 388 break; 389 case AudioManager.RINGER_MODE_VIBRATE: 390 case AudioManager.RINGER_MODE_NORMAL: 391 if (mZenMode != Global.ZEN_MODE_OFF) { 392 newZen = Global.ZEN_MODE_OFF; 393 } 394 break; 395 } 396 if (newZen != -1) { 397 mHandler.postSetZenMode(newZen, "ringerModeExternal"); 398 } 399 400 ZenLog.traceSetRingerModeExternal(ringerModeOld, ringerModeNew, caller, ringerModeInternal, 401 ringerModeInternalOut); 402 return ringerModeInternalOut; 403 } 404 405 private void dispatchOnConfigChanged() { 406 for (Callback callback : mCallbacks) { 407 callback.onConfigChanged(); 408 } 409 } 410 411 private void dispatchOnZenModeChanged() { 412 for (Callback callback : mCallbacks) { 413 callback.onZenModeChanged(); 414 } 415 } 416 417 private static boolean isSystem(NotificationRecord record) { 418 return record.isCategory(Notification.CATEGORY_SYSTEM); 419 } 420 421 private static boolean isAlarm(NotificationRecord record) { 422 return record.isCategory(Notification.CATEGORY_ALARM) 423 || record.isAudioStream(AudioManager.STREAM_ALARM) 424 || record.isAudioAttributesUsage(AudioAttributes.USAGE_ALARM); 425 } 426 427 private static boolean isEvent(NotificationRecord record) { 428 return record.isCategory(Notification.CATEGORY_EVENT); 429 } 430 431 public boolean isCall(NotificationRecord record) { 432 return record != null && (isDefaultPhoneApp(record.sbn.getPackageName()) 433 || record.isCategory(Notification.CATEGORY_CALL)); 434 } 435 436 private boolean isDefaultPhoneApp(String pkg) { 437 if (mDefaultPhoneApp == null) { 438 final TelecomManager telecomm = 439 (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE); 440 mDefaultPhoneApp = telecomm != null ? telecomm.getDefaultPhoneApp() : null; 441 if (DEBUG) Slog.d(TAG, "Default phone app: " + mDefaultPhoneApp); 442 } 443 return pkg != null && mDefaultPhoneApp != null 444 && pkg.equals(mDefaultPhoneApp.getPackageName()); 445 } 446 447 private boolean isDefaultMessagingApp(NotificationRecord record) { 448 final int userId = record.getUserId(); 449 if (userId == UserHandle.USER_NULL || userId == UserHandle.USER_ALL) return false; 450 final String defaultApp = Secure.getStringForUser(mContext.getContentResolver(), 451 Secure.SMS_DEFAULT_APPLICATION, userId); 452 return Objects.equals(defaultApp, record.sbn.getPackageName()); 453 } 454 455 private boolean isMessage(NotificationRecord record) { 456 return record.isCategory(Notification.CATEGORY_MESSAGE) || isDefaultMessagingApp(record); 457 } 458 459 /** 460 * @param extras extras of the notification with EXTRA_PEOPLE populated 461 * @param contactsTimeoutMs timeout in milliseconds to wait for contacts response 462 * @param timeoutAffinity affinity to return when the timeout specified via 463 * <code>contactsTimeoutMs</code> is hit 464 */ 465 public boolean matchesCallFilter(UserHandle userHandle, Bundle extras, 466 ValidateNotificationPeople validator, int contactsTimeoutMs, float timeoutAffinity) { 467 final int zen = mZenMode; 468 if (zen == Global.ZEN_MODE_NO_INTERRUPTIONS) return false; // nothing gets through 469 if (zen == Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS) { 470 if (!mConfig.allowCalls) return false; // no calls get through 471 if (validator != null) { 472 final float contactAffinity = validator.getContactAffinity(userHandle, extras, 473 contactsTimeoutMs, timeoutAffinity); 474 return audienceMatches(contactAffinity); 475 } 476 } 477 return true; 478 } 479 480 @Override 481 public String toString() { 482 return TAG; 483 } 484 485 private boolean audienceMatches(float contactAffinity) { 486 switch (mConfig.allowFrom) { 487 case ZenModeConfig.SOURCE_ANYONE: 488 return true; 489 case ZenModeConfig.SOURCE_CONTACT: 490 return contactAffinity >= ValidateNotificationPeople.VALID_CONTACT; 491 case ZenModeConfig.SOURCE_STAR: 492 return contactAffinity >= ValidateNotificationPeople.STARRED_CONTACT; 493 default: 494 Slog.w(TAG, "Encountered unknown source: " + mConfig.allowFrom); 495 return true; 496 } 497 } 498 499 private class SettingsObserver extends ContentObserver { 500 private final Uri ZEN_MODE = Global.getUriFor(Global.ZEN_MODE); 501 502 public SettingsObserver(Handler handler) { 503 super(handler); 504 } 505 506 public void observe() { 507 final ContentResolver resolver = mContext.getContentResolver(); 508 resolver.registerContentObserver(ZEN_MODE, false /*notifyForDescendents*/, this); 509 update(null); 510 } 511 512 @Override 513 public void onChange(boolean selfChange, Uri uri) { 514 update(uri); 515 } 516 517 public void update(Uri uri) { 518 if (ZEN_MODE.equals(uri)) { 519 updateZenMode(); 520 } 521 } 522 } 523 524 private class H extends Handler { 525 private static final int MSG_SET_ZEN = 1; 526 527 private H(Looper looper) { 528 super(looper); 529 } 530 531 private void postSetZenMode(int zen, String reason) { 532 obtainMessage(MSG_SET_ZEN, zen, 0, reason).sendToTarget(); 533 } 534 535 @Override 536 public void handleMessage(Message msg) { 537 switch(msg.what) { 538 case MSG_SET_ZEN: 539 setZenMode(msg.arg1, (String) msg.obj); 540 break; 541 } 542 } 543 } 544 545 public static class Callback { 546 void onConfigChanged() {} 547 void onZenModeChanged() {} 548 } 549} 550