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