ZenModeHelper.java revision e86de4c0670550a29edae77ebb9f5c8ba5631231
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 android.app.AlarmManager; 20import android.app.AppOpsManager; 21import android.app.Notification; 22import android.app.PendingIntent; 23import android.content.BroadcastReceiver; 24import android.content.ContentResolver; 25import android.content.Context; 26import android.content.Intent; 27import android.content.IntentFilter; 28import android.content.res.Resources; 29import android.content.res.XmlResourceParser; 30import android.database.ContentObserver; 31import android.media.AudioManager; 32import android.net.Uri; 33import android.os.Handler; 34import android.os.IBinder; 35import android.provider.Settings.Global; 36import android.service.notification.ZenModeConfig; 37import android.util.Slog; 38 39import com.android.internal.R; 40 41import libcore.io.IoUtils; 42 43import org.xmlpull.v1.XmlPullParser; 44import org.xmlpull.v1.XmlPullParserException; 45import org.xmlpull.v1.XmlSerializer; 46 47import java.io.IOException; 48import java.io.PrintWriter; 49import java.util.ArrayList; 50import java.util.Arrays; 51import java.util.Calendar; 52import java.util.Date; 53import java.util.HashSet; 54import java.util.Set; 55 56/** 57 * NotificationManagerService helper for functionality related to zen mode. 58 */ 59public class ZenModeHelper { 60 private static final String TAG = "ZenModeHelper"; 61 62 private static final String ACTION_ENTER_ZEN = "enter_zen"; 63 private static final int REQUEST_CODE_ENTER = 100; 64 private static final String ACTION_EXIT_ZEN = "exit_zen"; 65 private static final int REQUEST_CODE_EXIT = 101; 66 private static final String EXTRA_TIME = "time"; 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 int mZenMode; 76 private ZenModeConfig mConfig; 77 78 // temporary, until we update apps to provide metadata 79 private static final Set<String> CALL_PACKAGES = new HashSet<String>(Arrays.asList( 80 "com.google.android.dialer", 81 "com.android.phone" 82 )); 83 private static final Set<String> MESSAGE_PACKAGES = new HashSet<String>(Arrays.asList( 84 "com.google.android.talk", 85 "com.android.mms" 86 )); 87 private static final Set<String> ALARM_PACKAGES = new HashSet<String>(Arrays.asList( 88 "com.google.android.deskclock" 89 )); 90 91 public ZenModeHelper(Context context, Handler handler) { 92 mContext = context; 93 mHandler = handler; 94 mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); 95 mDefaultConfig = readDefaultConfig(context.getResources()); 96 mConfig = mDefaultConfig; 97 mSettingsObserver = new SettingsObserver(mHandler); 98 mSettingsObserver.observe(); 99 100 final IntentFilter filter = new IntentFilter(); 101 filter.addAction(ACTION_ENTER_ZEN); 102 filter.addAction(ACTION_EXIT_ZEN); 103 mContext.registerReceiver(new ZenBroadcastReceiver(), filter); 104 } 105 106 public static ZenModeConfig readDefaultConfig(Resources resources) { 107 XmlResourceParser parser = null; 108 try { 109 parser = resources.getXml(R.xml.default_zen_mode_config); 110 while (parser.next() != XmlPullParser.END_DOCUMENT) { 111 final ZenModeConfig config = ZenModeConfig.readXml(parser); 112 if (config != null) return config; 113 } 114 } catch (Exception e) { 115 Slog.w(TAG, "Error reading default zen mode config from resource", e); 116 } finally { 117 IoUtils.closeQuietly(parser); 118 } 119 return new ZenModeConfig(); 120 } 121 122 public void addCallback(Callback callback) { 123 mCallbacks.add(callback); 124 } 125 126 public boolean shouldIntercept(String pkg, Notification n) { 127 if (mZenMode != Global.ZEN_MODE_OFF) { 128 if (isAlarm(pkg, n)) { 129 return false; 130 } 131 if (isCall(pkg, n)) { 132 return !mConfig.allowCalls; 133 } 134 if (isMessage(pkg, n)) { 135 return !mConfig.allowMessages; 136 } 137 return true; 138 } 139 return false; 140 } 141 142 public int getZenMode() { 143 return mZenMode; 144 } 145 146 public void setZenMode(int zenModeValue) { 147 Global.putInt(mContext.getContentResolver(), Global.ZEN_MODE, zenModeValue); 148 } 149 150 public void updateZenMode() { 151 final int mode = Global.getInt(mContext.getContentResolver(), 152 Global.ZEN_MODE, Global.ZEN_MODE_OFF); 153 if (mode != mZenMode) { 154 Slog.d(TAG, String.format("updateZenMode: %s -> %s", 155 Global.zenModeToString(mZenMode), 156 Global.zenModeToString(mode))); 157 } 158 mZenMode = mode; 159 final boolean zen = mZenMode != Global.ZEN_MODE_OFF; 160 final String[] exceptionPackages = null; // none (for now) 161 162 // call restrictions 163 final boolean muteCalls = zen && !mConfig.allowCalls; 164 mAppOps.setRestriction(AppOpsManager.OP_VIBRATE, AudioManager.STREAM_RING, 165 muteCalls ? AppOpsManager.MODE_IGNORED : AppOpsManager.MODE_ALLOWED, 166 exceptionPackages); 167 mAppOps.setRestriction(AppOpsManager.OP_PLAY_AUDIO, AudioManager.STREAM_RING, 168 muteCalls ? AppOpsManager.MODE_IGNORED : AppOpsManager.MODE_ALLOWED, 169 exceptionPackages); 170 171 // restrict vibrations with no hints 172 mAppOps.setRestriction(AppOpsManager.OP_VIBRATE, AudioManager.USE_DEFAULT_STREAM_TYPE, 173 zen ? AppOpsManager.MODE_IGNORED : AppOpsManager.MODE_ALLOWED, 174 exceptionPackages); 175 dispatchOnZenModeChanged(); 176 } 177 178 public boolean allowDisable(int what, IBinder token, String pkg) { 179 if (isCall(pkg, null)) { 180 return mZenMode == Global.ZEN_MODE_OFF || mConfig.allowCalls; 181 } 182 return true; 183 } 184 185 public void dump(PrintWriter pw, String prefix) { 186 pw.print(prefix); pw.print("mZenMode="); 187 pw.println(Global.zenModeToString(mZenMode)); 188 pw.print(prefix); pw.print("mConfig="); pw.println(mConfig); 189 pw.print(prefix); pw.print("mDefaultConfig="); pw.println(mDefaultConfig); 190 } 191 192 public void readXml(XmlPullParser parser) throws XmlPullParserException, IOException { 193 final ZenModeConfig config = ZenModeConfig.readXml(parser); 194 if (config != null) { 195 setConfig(config); 196 } 197 } 198 199 public void writeXml(XmlSerializer out) throws IOException { 200 mConfig.writeXml(out); 201 } 202 203 public ZenModeConfig getConfig() { 204 return mConfig; 205 } 206 207 public boolean setConfig(ZenModeConfig config) { 208 if (config == null || !config.isValid()) return false; 209 if (config.equals(mConfig)) return true; 210 mConfig = config; 211 Slog.d(TAG, "mConfig=" + mConfig); 212 dispatchOnConfigChanged(); 213 final String val = Integer.toString(mConfig.hashCode()); 214 Global.putString(mContext.getContentResolver(), Global.ZEN_MODE_CONFIG_ETAG, val); 215 updateAlarms(); 216 updateZenMode(); 217 return true; 218 } 219 220 private void dispatchOnConfigChanged() { 221 for (Callback callback : mCallbacks) { 222 callback.onConfigChanged(); 223 } 224 } 225 226 private void dispatchOnZenModeChanged() { 227 for (Callback callback : mCallbacks) { 228 callback.onZenModeChanged(); 229 } 230 } 231 232 private boolean isAlarm(String pkg, Notification n) { 233 return ALARM_PACKAGES.contains(pkg); 234 } 235 236 private boolean isCall(String pkg, Notification n) { 237 return CALL_PACKAGES.contains(pkg); 238 } 239 240 private boolean isMessage(String pkg, Notification n) { 241 return MESSAGE_PACKAGES.contains(pkg); 242 } 243 244 private void updateAlarms() { 245 updateAlarm(ACTION_ENTER_ZEN, REQUEST_CODE_ENTER, 246 mConfig.sleepStartHour, mConfig.sleepStartMinute); 247 updateAlarm(ACTION_EXIT_ZEN, REQUEST_CODE_EXIT, 248 mConfig.sleepEndHour, mConfig.sleepEndMinute); 249 } 250 251 private void updateAlarm(String action, int requestCode, int hr, int min) { 252 final AlarmManager alarms = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE); 253 final long now = System.currentTimeMillis(); 254 final Calendar c = Calendar.getInstance(); 255 c.setTimeInMillis(now); 256 c.set(Calendar.HOUR_OF_DAY, hr); 257 c.set(Calendar.MINUTE, min); 258 c.set(Calendar.SECOND, 0); 259 c.set(Calendar.MILLISECOND, 0); 260 if (c.getTimeInMillis() <= now) { 261 c.add(Calendar.DATE, 1); 262 } 263 final long time = c.getTimeInMillis(); 264 final PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, requestCode, 265 new Intent(action).putExtra(EXTRA_TIME, time), PendingIntent.FLAG_UPDATE_CURRENT); 266 alarms.cancel(pendingIntent); 267 if (mConfig.sleepMode != null) { 268 Slog.d(TAG, String.format("Scheduling %s for %s, %s in the future, now=%s", 269 action, ts(time), time - now, ts(now))); 270 alarms.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent); 271 } 272 } 273 274 private static String ts(long time) { 275 return new Date(time) + " (" + time + ")"; 276 } 277 278 public static boolean isWeekend(long time, int offsetDays) { 279 final Calendar c = Calendar.getInstance(); 280 c.setTimeInMillis(time); 281 if (offsetDays != 0) { 282 c.add(Calendar.DATE, offsetDays); 283 } 284 final int day = c.get(Calendar.DAY_OF_WEEK); 285 return day == Calendar.SATURDAY || day == Calendar.SUNDAY; 286 } 287 288 private class SettingsObserver extends ContentObserver { 289 private final Uri ZEN_MODE = Global.getUriFor(Global.ZEN_MODE); 290 291 public SettingsObserver(Handler handler) { 292 super(handler); 293 } 294 295 public void observe() { 296 final ContentResolver resolver = mContext.getContentResolver(); 297 resolver.registerContentObserver(ZEN_MODE, false /*notifyForDescendents*/, this); 298 update(null); 299 } 300 301 @Override 302 public void onChange(boolean selfChange, Uri uri) { 303 update(uri); 304 } 305 306 public void update(Uri uri) { 307 if (ZEN_MODE.equals(uri)) { 308 updateZenMode(); 309 } 310 } 311 } 312 313 private class ZenBroadcastReceiver extends BroadcastReceiver { 314 @Override 315 public void onReceive(Context context, Intent intent) { 316 if (ACTION_ENTER_ZEN.equals(intent.getAction())) { 317 setZenMode(intent, 1, Global.ZEN_MODE_ON); 318 } else if (ACTION_EXIT_ZEN.equals(intent.getAction())) { 319 setZenMode(intent, 0, Global.ZEN_MODE_OFF); 320 } 321 } 322 323 private void setZenMode(Intent intent, int wkendOffsetDays, int zenModeValue) { 324 final long schTime = intent.getLongExtra(EXTRA_TIME, 0); 325 final long now = System.currentTimeMillis(); 326 Slog.d(TAG, String.format("%s scheduled for %s, fired at %s, delta=%s", 327 intent.getAction(), ts(schTime), ts(now), now - schTime)); 328 329 final boolean skip = ZenModeConfig.SLEEP_MODE_WEEKNIGHTS.equals(mConfig.sleepMode) && 330 isWeekend(schTime, wkendOffsetDays); 331 332 if (skip) { 333 Slog.d(TAG, "Skipping zen mode update for the weekend"); 334 } else { 335 ZenModeHelper.this.setZenMode(zenModeValue); 336 } 337 updateAlarms(); 338 } 339 } 340 341 public static class Callback { 342 void onConfigChanged() {} 343 void onZenModeChanged() {} 344 } 345} 346