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