ZenModeHelper.java revision 4db0d98b42a723f2e16c6595e85e866fd26c6d98
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_RINGTONE; 21import static android.media.AudioAttributes.USAGE_UNKNOWN; 22 23import android.app.AppOpsManager; 24import android.app.Notification; 25import android.content.BroadcastReceiver; 26import android.content.ComponentName; 27import android.content.ContentResolver; 28import android.content.Context; 29import android.content.Intent; 30import android.content.IntentFilter; 31import android.content.res.Resources; 32import android.content.res.XmlResourceParser; 33import android.database.ContentObserver; 34import android.media.AudioAttributes; 35import android.media.AudioManager; 36import android.net.Uri; 37import android.os.Handler; 38import android.os.IBinder; 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.telecomm.TelecommManager; 45import android.util.Log; 46import android.util.Slog; 47 48import com.android.internal.R; 49 50import libcore.io.IoUtils; 51 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.Objects; 60 61/** 62 * NotificationManagerService helper for functionality related to zen mode. 63 */ 64public class ZenModeHelper { 65 private static final String TAG = "ZenModeHelper"; 66 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG); 67 68 private final Context mContext; 69 private final Handler mHandler; 70 private final SettingsObserver mSettingsObserver; 71 private final AppOpsManager mAppOps; 72 private final ZenModeConfig mDefaultConfig; 73 private final ArrayList<Callback> mCallbacks = new ArrayList<Callback>(); 74 75 private ComponentName mDefaultPhoneApp; 76 private int mZenMode; 77 private ZenModeConfig mConfig; 78 private AudioManager mAudioManager; 79 private int mPreviousRingerMode = -1; 80 81 public ZenModeHelper(Context context, Handler handler) { 82 mContext = context; 83 mHandler = handler; 84 mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); 85 mDefaultConfig = readDefaultConfig(context.getResources()); 86 mConfig = mDefaultConfig; 87 mSettingsObserver = new SettingsObserver(mHandler); 88 mSettingsObserver.observe(); 89 90 final IntentFilter filter = new IntentFilter(); 91 filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); 92 mContext.registerReceiver(mReceiver, filter); 93 } 94 95 public static ZenModeConfig readDefaultConfig(Resources resources) { 96 XmlResourceParser parser = null; 97 try { 98 parser = resources.getXml(R.xml.default_zen_mode_config); 99 while (parser.next() != XmlPullParser.END_DOCUMENT) { 100 final ZenModeConfig config = ZenModeConfig.readXml(parser); 101 if (config != null) return config; 102 } 103 } catch (Exception e) { 104 Slog.w(TAG, "Error reading default zen mode config from resource", e); 105 } finally { 106 IoUtils.closeQuietly(parser); 107 } 108 return new ZenModeConfig(); 109 } 110 111 public void addCallback(Callback callback) { 112 mCallbacks.add(callback); 113 } 114 115 public void setAudioManager(AudioManager audioManager) { 116 mAudioManager = audioManager; 117 } 118 119 public int getZenModeListenerHint() { 120 switch(mZenMode) { 121 case Global.ZEN_MODE_OFF: 122 return NotificationListenerService.HINT_HOST_INTERRUPTION_LEVEL_ALL; 123 case Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS: 124 return NotificationListenerService.HINT_HOST_INTERRUPTION_LEVEL_PRIORITY; 125 case Global.ZEN_MODE_NO_INTERRUPTIONS: 126 return NotificationListenerService.HINT_HOST_INTERRUPTION_LEVEL_NONE; 127 default: 128 return 0; 129 } 130 } 131 132 private static int zenFromListenerHint(int hints, int defValue) { 133 final int level = hints & NotificationListenerService.HOST_INTERRUPTION_LEVEL_MASK; 134 switch(level) { 135 case NotificationListenerService.HINT_HOST_INTERRUPTION_LEVEL_ALL: 136 return Global.ZEN_MODE_OFF; 137 case NotificationListenerService.HINT_HOST_INTERRUPTION_LEVEL_PRIORITY: 138 return Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS; 139 case NotificationListenerService.HINT_HOST_INTERRUPTION_LEVEL_NONE: 140 return Global.ZEN_MODE_NO_INTERRUPTIONS; 141 default: 142 return defValue; 143 } 144 } 145 146 public void requestFromListener(int hints) { 147 final int newZen = zenFromListenerHint(hints, -1); 148 if (newZen != -1) { 149 setZenMode(newZen, "listener"); 150 } 151 } 152 153 public boolean shouldIntercept(NotificationRecord record) { 154 if (mZenMode != Global.ZEN_MODE_OFF) { 155 if (isSystem(record)) { 156 return false; 157 } 158 if (isAlarm(record)) { 159 if (mZenMode == Global.ZEN_MODE_NO_INTERRUPTIONS) { 160 ZenLog.traceIntercepted(record, "alarm"); 161 return true; 162 } 163 return false; 164 } 165 // allow user-prioritized packages through in priority mode 166 if (mZenMode == Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS) { 167 if (record.getPackagePriority() == Notification.PRIORITY_MAX) { 168 ZenLog.traceNotIntercepted(record, "priorityApp"); 169 return false; 170 } 171 } 172 // audience has veto power over all following rules 173 if (!audienceMatches(record)) { 174 ZenLog.traceIntercepted(record, "!audienceMatches"); 175 return true; 176 } 177 if (isCall(record)) { 178 if (!mConfig.allowCalls) { 179 ZenLog.traceIntercepted(record, "!allowCalls"); 180 return true; 181 } 182 return false; 183 } 184 if (isMessage(record)) { 185 if (!mConfig.allowMessages) { 186 ZenLog.traceIntercepted(record, "!allowMessages"); 187 return true; 188 } 189 return false; 190 } 191 ZenLog.traceIntercepted(record, "!allowed"); 192 return true; 193 } 194 return false; 195 } 196 197 public int getZenMode() { 198 return mZenMode; 199 } 200 201 public void setZenMode(int zenModeValue, String reason) { 202 ZenLog.traceSetZenMode(zenModeValue, reason); 203 Global.putInt(mContext.getContentResolver(), Global.ZEN_MODE, zenModeValue); 204 } 205 206 public void updateZenMode() { 207 final int mode = Global.getInt(mContext.getContentResolver(), 208 Global.ZEN_MODE, Global.ZEN_MODE_OFF); 209 if (mode != mZenMode) { 210 ZenLog.traceUpdateZenMode(mZenMode, mode); 211 } 212 mZenMode = mode; 213 final boolean zen = mZenMode != Global.ZEN_MODE_OFF; 214 final String[] exceptionPackages = null; // none (for now) 215 216 // call restrictions 217 final boolean muteCalls = zen && !mConfig.allowCalls; 218 mAppOps.setRestriction(AppOpsManager.OP_VIBRATE, USAGE_NOTIFICATION_RINGTONE, 219 muteCalls ? AppOpsManager.MODE_IGNORED : AppOpsManager.MODE_ALLOWED, 220 exceptionPackages); 221 mAppOps.setRestriction(AppOpsManager.OP_PLAY_AUDIO, USAGE_NOTIFICATION_RINGTONE, 222 muteCalls ? AppOpsManager.MODE_IGNORED : AppOpsManager.MODE_ALLOWED, 223 exceptionPackages); 224 225 // restrict vibrations with no hints 226 mAppOps.setRestriction(AppOpsManager.OP_VIBRATE, USAGE_UNKNOWN, 227 zen ? AppOpsManager.MODE_IGNORED : AppOpsManager.MODE_ALLOWED, 228 exceptionPackages); 229 230 // alarm restrictions 231 final boolean muteAlarms = mZenMode == Global.ZEN_MODE_NO_INTERRUPTIONS; 232 mAppOps.setRestriction(AppOpsManager.OP_VIBRATE, USAGE_ALARM, 233 muteAlarms ? AppOpsManager.MODE_IGNORED : AppOpsManager.MODE_ALLOWED, 234 exceptionPackages); 235 mAppOps.setRestriction(AppOpsManager.OP_PLAY_AUDIO, USAGE_ALARM, 236 muteAlarms ? AppOpsManager.MODE_IGNORED : AppOpsManager.MODE_ALLOWED, 237 exceptionPackages); 238 239 // force ringer mode into compliance 240 if (mAudioManager != null) { 241 int ringerMode = mAudioManager.getRingerMode(); 242 int forcedRingerMode = -1; 243 if (mZenMode == Global.ZEN_MODE_NO_INTERRUPTIONS) { 244 if (ringerMode != AudioManager.RINGER_MODE_SILENT) { 245 mPreviousRingerMode = ringerMode; 246 if (DEBUG) Slog.d(TAG, "Silencing ringer"); 247 forcedRingerMode = AudioManager.RINGER_MODE_SILENT; 248 } 249 } else { 250 if (ringerMode == AudioManager.RINGER_MODE_SILENT) { 251 if (DEBUG) Slog.d(TAG, "Unsilencing ringer"); 252 forcedRingerMode = mPreviousRingerMode != -1 ? mPreviousRingerMode 253 : AudioManager.RINGER_MODE_NORMAL; 254 mPreviousRingerMode = -1; 255 } 256 } 257 if (forcedRingerMode != -1) { 258 mAudioManager.setRingerMode(forcedRingerMode); 259 ZenLog.traceSetRingerMode(forcedRingerMode); 260 } 261 } 262 dispatchOnZenModeChanged(); 263 } 264 265 public boolean allowDisable(int what, IBinder token, String pkg) { 266 // TODO(cwren): delete this API before the next release. Bug:15344099 267 boolean allowDisable = true; 268 String reason = null; 269 if (isDefaultPhoneApp(pkg)) { 270 allowDisable = mZenMode == Global.ZEN_MODE_OFF || mConfig.allowCalls; 271 reason = mZenMode == Global.ZEN_MODE_OFF ? "zenOff" : "allowCalls"; 272 } 273 ZenLog.traceAllowDisable(pkg, allowDisable, reason); 274 return allowDisable; 275 } 276 277 public void dump(PrintWriter pw, String prefix) { 278 pw.print(prefix); pw.print("mZenMode="); 279 pw.println(Global.zenModeToString(mZenMode)); 280 pw.print(prefix); pw.print("mConfig="); pw.println(mConfig); 281 pw.print(prefix); pw.print("mDefaultConfig="); pw.println(mDefaultConfig); 282 pw.print(prefix); pw.print("mPreviousRingerMode="); pw.println(mPreviousRingerMode); 283 pw.print(prefix); pw.print("mDefaultPhoneApp="); pw.println(mDefaultPhoneApp); 284 } 285 286 public void readXml(XmlPullParser parser) throws XmlPullParserException, IOException { 287 final ZenModeConfig config = ZenModeConfig.readXml(parser); 288 if (config != null) { 289 setConfig(config); 290 } 291 } 292 293 public void writeXml(XmlSerializer out) throws IOException { 294 mConfig.writeXml(out); 295 } 296 297 public ZenModeConfig getConfig() { 298 return mConfig; 299 } 300 301 public boolean setConfig(ZenModeConfig config) { 302 if (config == null || !config.isValid()) return false; 303 if (config.equals(mConfig)) return true; 304 ZenLog.traceConfig(mConfig, config); 305 mConfig = config; 306 dispatchOnConfigChanged(); 307 final String val = Integer.toString(mConfig.hashCode()); 308 Global.putString(mContext.getContentResolver(), Global.ZEN_MODE_CONFIG_ETAG, val); 309 updateZenMode(); 310 return true; 311 } 312 313 private void handleRingerModeChanged() { 314 if (mAudioManager != null) { 315 // follow ringer mode if necessary 316 final int ringerMode = mAudioManager.getRingerMode(); 317 int newZen = -1; 318 if (ringerMode == AudioManager.RINGER_MODE_SILENT) { 319 if (mZenMode != Global.ZEN_MODE_NO_INTERRUPTIONS) { 320 newZen = Global.ZEN_MODE_NO_INTERRUPTIONS; 321 } 322 } else if ((ringerMode == AudioManager.RINGER_MODE_NORMAL 323 || ringerMode == AudioManager.RINGER_MODE_VIBRATE) 324 && mZenMode == Global.ZEN_MODE_NO_INTERRUPTIONS) { 325 newZen = Global.ZEN_MODE_OFF; 326 } 327 if (newZen != -1) { 328 ZenLog.traceFollowRingerMode(ringerMode, mZenMode, newZen); 329 setZenMode(newZen, "ringerMode"); 330 } 331 } 332 } 333 334 private void dispatchOnConfigChanged() { 335 for (Callback callback : mCallbacks) { 336 callback.onConfigChanged(); 337 } 338 } 339 340 private void dispatchOnZenModeChanged() { 341 for (Callback callback : mCallbacks) { 342 callback.onZenModeChanged(); 343 } 344 } 345 346 private boolean isSystem(NotificationRecord record) { 347 return record.isCategory(Notification.CATEGORY_SYSTEM); 348 } 349 350 private boolean isAlarm(NotificationRecord record) { 351 return record.isCategory(Notification.CATEGORY_ALARM) 352 || record.isCategory(Notification.CATEGORY_EVENT) 353 || record.isAudioStream(AudioManager.STREAM_ALARM) 354 || record.isAudioAttributesUsage(AudioAttributes.USAGE_ALARM); 355 } 356 357 private boolean isCall(NotificationRecord record) { 358 return isDefaultPhoneApp(record.sbn.getPackageName()) 359 || record.isCategory(Notification.CATEGORY_CALL); 360 } 361 362 private boolean isDefaultPhoneApp(String pkg) { 363 if (mDefaultPhoneApp == null) { 364 final TelecommManager telecomm = 365 (TelecommManager) mContext.getSystemService(Context.TELECOMM_SERVICE); 366 mDefaultPhoneApp = telecomm != null ? telecomm.getDefaultPhoneApp() : null; 367 if (DEBUG) Slog.d(TAG, "Default phone app: " + mDefaultPhoneApp); 368 } 369 return pkg != null && mDefaultPhoneApp != null 370 && pkg.equals(mDefaultPhoneApp.getPackageName()); 371 } 372 373 private boolean isDefaultMessagingApp(NotificationRecord record) { 374 final int userId = record.getUserId(); 375 if (userId == UserHandle.USER_NULL || userId == UserHandle.USER_ALL) return false; 376 final String defaultApp = Secure.getStringForUser(mContext.getContentResolver(), 377 Secure.SMS_DEFAULT_APPLICATION, userId); 378 return Objects.equals(defaultApp, record.sbn.getPackageName()); 379 } 380 381 private boolean isMessage(NotificationRecord record) { 382 return record.isCategory(Notification.CATEGORY_MESSAGE) || isDefaultMessagingApp(record); 383 } 384 385 private boolean audienceMatches(NotificationRecord record) { 386 switch (mConfig.allowFrom) { 387 case ZenModeConfig.SOURCE_ANYONE: 388 return true; 389 case ZenModeConfig.SOURCE_CONTACT: 390 return record.getContactAffinity() >= ValidateNotificationPeople.VALID_CONTACT; 391 case ZenModeConfig.SOURCE_STAR: 392 return record.getContactAffinity() >= ValidateNotificationPeople.STARRED_CONTACT; 393 default: 394 Slog.w(TAG, "Encountered unknown source: " + mConfig.allowFrom); 395 return true; 396 } 397 } 398 399 private final Runnable mRingerModeChanged = new Runnable() { 400 @Override 401 public void run() { 402 handleRingerModeChanged(); 403 } 404 }; 405 406 private class SettingsObserver extends ContentObserver { 407 private final Uri ZEN_MODE = Global.getUriFor(Global.ZEN_MODE); 408 409 public SettingsObserver(Handler handler) { 410 super(handler); 411 } 412 413 public void observe() { 414 final ContentResolver resolver = mContext.getContentResolver(); 415 resolver.registerContentObserver(ZEN_MODE, false /*notifyForDescendents*/, this); 416 update(null); 417 } 418 419 @Override 420 public void onChange(boolean selfChange, Uri uri) { 421 update(uri); 422 } 423 424 public void update(Uri uri) { 425 if (ZEN_MODE.equals(uri)) { 426 updateZenMode(); 427 } 428 } 429 } 430 431 private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 432 @Override 433 public void onReceive(Context context, Intent intent) { 434 mHandler.post(mRingerModeChanged); 435 } 436 }; 437 438 public static class Callback { 439 void onConfigChanged() {} 440 void onZenModeChanged() {} 441 } 442} 443