ZenModeHelper.java revision 8403b7535b7b13e5aed732963fc49cf477b9a92e
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 (mZenMode != Global.ZEN_MODE_OFF) {
351                    ringerModeExternalOut = AudioManager.RINGER_MODE_SILENT;
352                }
353                break;
354        }
355        if (newZen != -1) {
356            mHandler.postSetZenMode(newZen, "ringerModeInternal");
357        }
358
359        if (isChange || newZen != -1 || ringerModeExternal != ringerModeExternalOut) {
360            ZenLog.traceSetRingerModeInternal(ringerModeOld, ringerModeNew, caller,
361                    ringerModeExternal, ringerModeExternalOut);
362        }
363        return ringerModeExternalOut;
364    }
365
366    @Override  // RingerModeDelegate
367    public int onSetRingerModeExternal(int ringerModeOld, int ringerModeNew, String caller,
368            int ringerModeInternal) {
369        int ringerModeInternalOut = ringerModeNew;
370        final boolean isChange = ringerModeOld != ringerModeNew;
371        final boolean isVibrate = ringerModeInternal == AudioManager.RINGER_MODE_VIBRATE;
372
373        int newZen = -1;
374        switch(ringerModeNew) {
375            case AudioManager.RINGER_MODE_SILENT:
376                if (isChange) {
377                    if (mZenMode == Global.ZEN_MODE_OFF) {
378                        newZen = Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS;
379                    }
380                    ringerModeInternalOut = isVibrate ? AudioManager.RINGER_MODE_VIBRATE
381                            : AudioManager.RINGER_MODE_NORMAL;
382                } else {
383                    ringerModeInternalOut = ringerModeInternal;
384                }
385                break;
386            case AudioManager.RINGER_MODE_VIBRATE:
387            case AudioManager.RINGER_MODE_NORMAL:
388                if (mZenMode != Global.ZEN_MODE_OFF) {
389                    newZen = Global.ZEN_MODE_OFF;
390                }
391                break;
392        }
393        if (newZen != -1) {
394            mHandler.postSetZenMode(newZen, "ringerModeExternal");
395        }
396
397        ZenLog.traceSetRingerModeExternal(ringerModeOld, ringerModeNew, caller, ringerModeInternal,
398                ringerModeInternalOut);
399        return ringerModeInternalOut;
400    }
401
402    private void dispatchOnConfigChanged() {
403        for (Callback callback : mCallbacks) {
404            callback.onConfigChanged();
405        }
406    }
407
408    private void dispatchOnZenModeChanged() {
409        for (Callback callback : mCallbacks) {
410            callback.onZenModeChanged();
411        }
412    }
413
414    private static boolean isSystem(NotificationRecord record) {
415        return record.isCategory(Notification.CATEGORY_SYSTEM);
416    }
417
418    private static boolean isAlarm(NotificationRecord record) {
419        return record.isCategory(Notification.CATEGORY_ALARM)
420                || record.isAudioStream(AudioManager.STREAM_ALARM)
421                || record.isAudioAttributesUsage(AudioAttributes.USAGE_ALARM);
422    }
423
424    private static boolean isEvent(NotificationRecord record) {
425        return record.isCategory(Notification.CATEGORY_EVENT);
426    }
427
428    public boolean isCall(NotificationRecord record) {
429        return record != null && (isDefaultPhoneApp(record.sbn.getPackageName())
430                || record.isCategory(Notification.CATEGORY_CALL));
431    }
432
433    private boolean isDefaultPhoneApp(String pkg) {
434        if (mDefaultPhoneApp == null) {
435            final TelecomManager telecomm =
436                    (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
437            mDefaultPhoneApp = telecomm != null ? telecomm.getDefaultPhoneApp() : null;
438            if (DEBUG) Slog.d(TAG, "Default phone app: " + mDefaultPhoneApp);
439        }
440        return pkg != null && mDefaultPhoneApp != null
441                && pkg.equals(mDefaultPhoneApp.getPackageName());
442    }
443
444    private boolean isDefaultMessagingApp(NotificationRecord record) {
445        final int userId = record.getUserId();
446        if (userId == UserHandle.USER_NULL || userId == UserHandle.USER_ALL) return false;
447        final String defaultApp = Secure.getStringForUser(mContext.getContentResolver(),
448                Secure.SMS_DEFAULT_APPLICATION, userId);
449        return Objects.equals(defaultApp, record.sbn.getPackageName());
450    }
451
452    private boolean isMessage(NotificationRecord record) {
453        return record.isCategory(Notification.CATEGORY_MESSAGE) || isDefaultMessagingApp(record);
454    }
455
456    /**
457     * @param extras extras of the notification with EXTRA_PEOPLE populated
458     * @param contactsTimeoutMs timeout in milliseconds to wait for contacts response
459     * @param timeoutAffinity affinity to return when the timeout specified via
460     *                        <code>contactsTimeoutMs</code> is hit
461     */
462    public boolean matchesCallFilter(UserHandle userHandle, Bundle extras,
463            ValidateNotificationPeople validator, int contactsTimeoutMs, float timeoutAffinity) {
464        final int zen = mZenMode;
465        if (zen == Global.ZEN_MODE_NO_INTERRUPTIONS) return false; // nothing gets through
466        if (zen == Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS) {
467            if (!mConfig.allowCalls) return false; // no calls get through
468            if (validator != null) {
469                final float contactAffinity = validator.getContactAffinity(userHandle, extras,
470                        contactsTimeoutMs, timeoutAffinity);
471                return audienceMatches(contactAffinity);
472            }
473        }
474        return true;
475    }
476
477    @Override
478    public String toString() {
479        return TAG;
480    }
481
482    private boolean audienceMatches(float contactAffinity) {
483        switch (mConfig.allowFrom) {
484            case ZenModeConfig.SOURCE_ANYONE:
485                return true;
486            case ZenModeConfig.SOURCE_CONTACT:
487                return contactAffinity >= ValidateNotificationPeople.VALID_CONTACT;
488            case ZenModeConfig.SOURCE_STAR:
489                return contactAffinity >= ValidateNotificationPeople.STARRED_CONTACT;
490            default:
491                Slog.w(TAG, "Encountered unknown source: " + mConfig.allowFrom);
492                return true;
493        }
494    }
495
496    private class SettingsObserver extends ContentObserver {
497        private final Uri ZEN_MODE = Global.getUriFor(Global.ZEN_MODE);
498
499        public SettingsObserver(Handler handler) {
500            super(handler);
501        }
502
503        public void observe() {
504            final ContentResolver resolver = mContext.getContentResolver();
505            resolver.registerContentObserver(ZEN_MODE, false /*notifyForDescendents*/, this);
506            update(null);
507        }
508
509        @Override
510        public void onChange(boolean selfChange, Uri uri) {
511            update(uri);
512        }
513
514        public void update(Uri uri) {
515            if (ZEN_MODE.equals(uri)) {
516                updateZenMode();
517            }
518        }
519    }
520
521    private class H extends Handler {
522        private static final int MSG_SET_ZEN = 1;
523
524        private H(Looper looper) {
525            super(looper);
526        }
527
528        private void postSetZenMode(int zen, String reason) {
529            obtainMessage(MSG_SET_ZEN, zen, 0, reason).sendToTarget();
530        }
531
532        @Override
533        public void handleMessage(Message msg) {
534            switch(msg.what) {
535                case MSG_SET_ZEN:
536                    setZenMode(msg.arg1, (String) msg.obj);
537                    break;
538            }
539        }
540    }
541
542    public static class Callback {
543        void onConfigChanged() {}
544        void onZenModeChanged() {}
545    }
546}
547