ScheduleConditionProvider.java revision 7f73308f50791740beb380fecc17903301054ad3
1/*
2 * Copyright (C) 2015 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.ActivityManager;
20import android.app.AlarmManager;
21import android.app.PendingIntent;
22import android.content.BroadcastReceiver;
23import android.content.ComponentName;
24import android.content.Context;
25import android.content.Intent;
26import android.content.IntentFilter;
27import android.net.Uri;
28import android.service.notification.Condition;
29import android.service.notification.IConditionProvider;
30import android.service.notification.ZenModeConfig;
31import android.service.notification.ZenModeConfig.ScheduleInfo;
32import android.util.ArrayMap;
33import android.util.Log;
34import android.util.Slog;
35
36import com.android.server.notification.NotificationManagerService.DumpFilter;
37
38import java.io.PrintWriter;
39import java.util.TimeZone;
40
41/**
42 * Built-in zen condition provider for daily scheduled time-based conditions.
43 */
44public class ScheduleConditionProvider extends SystemConditionProviderService {
45    private static final String TAG = "ConditionProviders.SCP";
46    private static final boolean DEBUG = true || Log.isLoggable("ConditionProviders", Log.DEBUG);
47
48    public static final ComponentName COMPONENT =
49            new ComponentName("android", ScheduleConditionProvider.class.getName());
50    private static final String NOT_SHOWN = "...";
51    private static final String SIMPLE_NAME = ScheduleConditionProvider.class.getSimpleName();
52    private static final String ACTION_EVALUATE =  SIMPLE_NAME + ".EVALUATE";
53    private static final int REQUEST_CODE_EVALUATE = 1;
54    private static final String EXTRA_TIME = "time";
55
56    private final Context mContext = this;
57    private final ArrayMap<Uri, ScheduleCalendar> mSubscriptions = new ArrayMap<>();
58
59    private AlarmManager mAlarmManager;
60    private boolean mConnected;
61    private boolean mRegistered;
62    private long mNextAlarmTime;
63
64    public ScheduleConditionProvider() {
65        if (DEBUG) Slog.d(TAG, "new " + SIMPLE_NAME + "()");
66    }
67
68    @Override
69    public ComponentName getComponent() {
70        return COMPONENT;
71    }
72
73    @Override
74    public boolean isValidConditionId(Uri id) {
75        return ZenModeConfig.isValidScheduleConditionId(id);
76    }
77
78    @Override
79    public void dump(PrintWriter pw, DumpFilter filter) {
80        pw.print("    "); pw.print(SIMPLE_NAME); pw.println(":");
81        pw.print("      mConnected="); pw.println(mConnected);
82        pw.print("      mRegistered="); pw.println(mRegistered);
83        pw.println("      mSubscriptions=");
84        final long now = System.currentTimeMillis();
85        for (Uri conditionId : mSubscriptions.keySet()) {
86            pw.print("        ");
87            pw.print(meetsSchedule(mSubscriptions.get(conditionId), now) ? "* " : "  ");
88            pw.println(conditionId);
89            pw.print("            ");
90            pw.println(mSubscriptions.get(conditionId).toString());
91        }
92        dumpUpcomingTime(pw, "mNextAlarmTime", mNextAlarmTime, now);
93    }
94
95    @Override
96    public void onConnected() {
97        if (DEBUG) Slog.d(TAG, "onConnected");
98        mConnected = true;
99    }
100
101    @Override
102    public void onBootComplete() {
103        // noop
104    }
105
106    @Override
107    public void onDestroy() {
108        super.onDestroy();
109        if (DEBUG) Slog.d(TAG, "onDestroy");
110        mConnected = false;
111    }
112
113    @Override
114    public void onSubscribe(Uri conditionId) {
115        if (DEBUG) Slog.d(TAG, "onSubscribe " + conditionId);
116        if (!ZenModeConfig.isValidScheduleConditionId(conditionId)) {
117            notifyCondition(conditionId, Condition.STATE_FALSE, "badCondition");
118            return;
119        }
120        mSubscriptions.put(conditionId, toScheduleCalendar(conditionId));
121        evaluateSubscriptions();
122    }
123
124    @Override
125    public void onUnsubscribe(Uri conditionId) {
126        if (DEBUG) Slog.d(TAG, "onUnsubscribe " + conditionId);
127        mSubscriptions.remove(conditionId);
128        evaluateSubscriptions();
129    }
130
131    @Override
132    public void attachBase(Context base) {
133        attachBaseContext(base);
134    }
135
136    @Override
137    public IConditionProvider asInterface() {
138        return (IConditionProvider) onBind(null);
139    }
140
141    private void evaluateSubscriptions() {
142        if (mAlarmManager == null) {
143            mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
144        }
145        setRegistered(!mSubscriptions.isEmpty());
146        final long now = System.currentTimeMillis();
147        mNextAlarmTime = 0;
148        long nextUserAlarmTime = getNextAlarm();
149        for (Uri conditionId : mSubscriptions.keySet()) {
150            final ScheduleCalendar cal = mSubscriptions.get(conditionId);
151            if (cal != null && cal.isInSchedule(now)) {
152                notifyCondition(conditionId, Condition.STATE_TRUE, "meetsSchedule");
153                cal.maybeSetNextAlarm(now, nextUserAlarmTime);
154            } else {
155                notifyCondition(conditionId, Condition.STATE_FALSE, "!meetsSchedule");
156            }
157            if (cal != null) {
158                final long nextChangeTime = cal.getNextChangeTime(now);
159                if (nextChangeTime > 0 && nextChangeTime > now) {
160                    if (mNextAlarmTime == 0 || nextChangeTime < mNextAlarmTime) {
161                        mNextAlarmTime = nextChangeTime;
162                    }
163                }
164            }
165        }
166        updateAlarm(now, mNextAlarmTime);
167    }
168
169    private void updateAlarm(long now, long time) {
170        final AlarmManager alarms = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
171        final PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext,
172                REQUEST_CODE_EVALUATE,
173                new Intent(ACTION_EVALUATE)
174                        .addFlags(Intent.FLAG_RECEIVER_FOREGROUND)
175                        .putExtra(EXTRA_TIME, time),
176                PendingIntent.FLAG_UPDATE_CURRENT);
177        alarms.cancel(pendingIntent);
178        if (time > now) {
179            if (DEBUG) Slog.d(TAG, String.format("Scheduling evaluate for %s, in %s, now=%s",
180                    ts(time), formatDuration(time - now), ts(now)));
181            alarms.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent);
182        } else {
183            if (DEBUG) Slog.d(TAG, "Not scheduling evaluate");
184        }
185    }
186
187    public long getNextAlarm() {
188        final AlarmManager.AlarmClockInfo info = mAlarmManager.getNextAlarmClock(
189                ActivityManager.getCurrentUser());
190        return info != null ? info.getTriggerTime() : 0;
191    }
192
193    private static boolean meetsSchedule(ScheduleCalendar cal, long time) {
194        return cal != null && cal.isInSchedule(time);
195    }
196
197    private static ScheduleCalendar toScheduleCalendar(Uri conditionId) {
198        final ScheduleInfo schedule = ZenModeConfig.tryParseScheduleConditionId(conditionId);
199        if (schedule == null || schedule.days == null || schedule.days.length == 0) return null;
200        final ScheduleCalendar sc = new ScheduleCalendar();
201        sc.setSchedule(schedule);
202        sc.setTimeZone(TimeZone.getDefault());
203        return sc;
204    }
205
206    private void setRegistered(boolean registered) {
207        if (mRegistered == registered) return;
208        if (DEBUG) Slog.d(TAG, "setRegistered " + registered);
209        mRegistered = registered;
210        if (mRegistered) {
211            final IntentFilter filter = new IntentFilter();
212            filter.addAction(Intent.ACTION_TIME_CHANGED);
213            filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
214            filter.addAction(ACTION_EVALUATE);
215            filter.addAction(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED);
216            registerReceiver(mReceiver, filter);
217        } else {
218            unregisterReceiver(mReceiver);
219        }
220    }
221
222    private void notifyCondition(Uri conditionId, int state, String reason) {
223        if (DEBUG) Slog.d(TAG, "notifyCondition " + conditionId
224                + " " + Condition.stateToString(state)
225                + " reason=" + reason);
226        notifyCondition(createCondition(conditionId, state));
227    }
228
229    private Condition createCondition(Uri id, int state) {
230        final String summary = NOT_SHOWN;
231        final String line1 = NOT_SHOWN;
232        final String line2 = NOT_SHOWN;
233        return new Condition(id, summary, line1, line2, 0, state, Condition.FLAG_RELEVANT_ALWAYS);
234    }
235
236    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
237        @Override
238        public void onReceive(Context context, Intent intent) {
239            if (DEBUG) Slog.d(TAG, "onReceive " + intent.getAction());
240            evaluateSubscriptions();
241        }
242    };
243
244}
245