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