AlertActivity.java revision 0e1e62408b96e1532eb6f6a609ae4c817751aaf3
1/*
2 * Copyright (C) 2007 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.calendar.alerts;
18
19import com.android.calendar.AsyncQueryService;
20import com.android.calendar.R;
21import com.android.calendar.Utils;
22
23import android.app.Activity;
24import android.app.AlarmManager;
25import android.app.NotificationManager;
26import android.content.ContentValues;
27import android.content.Context;
28import android.content.Intent;
29import android.database.Cursor;
30import android.net.Uri;
31import android.net.Uri.Builder;
32import android.os.Bundle;
33import android.provider.Calendar;
34import android.provider.Calendar.CalendarAlerts;
35import android.provider.Calendar.CalendarAlertsColumns;
36import android.util.Log;
37import android.view.View;
38import android.view.View.OnClickListener;
39import android.view.ViewGroup;
40import android.view.WindowManager;
41import android.widget.AdapterView;
42import android.widget.AdapterView.OnItemClickListener;
43import android.widget.Button;
44import android.widget.ListView;
45
46/**
47 * The alert panel that pops up when there is a calendar event alarm.
48 * This activity is started by an intent that specifies an event id.
49  */
50public class AlertActivity extends Activity implements OnClickListener {
51    private static final String TAG = "AlertActivity";
52
53    // The default snooze delay: 5 minutes
54    public static final long SNOOZE_DELAY = 5 * 60 * 1000L;
55
56    private static final String[] PROJECTION = new String[] {
57        CalendarAlerts._ID,              // 0
58        CalendarAlerts.TITLE,            // 1
59        CalendarAlerts.EVENT_LOCATION,   // 2
60        CalendarAlerts.ALL_DAY,          // 3
61        CalendarAlerts.BEGIN,            // 4
62        CalendarAlerts.END,              // 5
63        CalendarAlerts.EVENT_ID,         // 6
64        CalendarAlerts.CALENDAR_COLOR,            // 7
65        CalendarAlerts.RRULE,            // 8
66        CalendarAlerts.HAS_ALARM,        // 9
67        CalendarAlerts.STATE,            // 10
68        CalendarAlerts.ALARM_TIME,       // 11
69    };
70
71    public static final int INDEX_ROW_ID = 0;
72    public static final int INDEX_TITLE = 1;
73    public static final int INDEX_EVENT_LOCATION = 2;
74    public static final int INDEX_ALL_DAY = 3;
75    public static final int INDEX_BEGIN = 4;
76    public static final int INDEX_END = 5;
77    public static final int INDEX_EVENT_ID = 6;
78    public static final int INDEX_COLOR = 7;
79    public static final int INDEX_RRULE = 8;
80    public static final int INDEX_HAS_ALARM = 9;
81    public static final int INDEX_STATE = 10;
82    public static final int INDEX_ALARM_TIME = 11;
83
84    private static final String SELECTION = CalendarAlerts.STATE + "=?";
85    private static final String[] SELECTIONARG = new String[] {
86        Integer.toString(CalendarAlerts.FIRED)
87    };
88
89    // We use one notification id for all events so that we don't clutter
90    // the notification screen.  It doesn't matter what the id is, as long
91    // as it is used consistently everywhere.
92    public static final int NOTIFICATION_ID = 0;
93
94    private AlertAdapter mAdapter;
95    private QueryHandler mQueryHandler;
96    private Cursor mCursor;
97    private ListView mListView;
98    private Button mSnoozeAllButton;
99    private Button mDismissAllButton;
100
101
102    private void dismissFiredAlarms() {
103        ContentValues values = new ContentValues(1 /* size */);
104        values.put(PROJECTION[INDEX_STATE], CalendarAlerts.DISMISSED);
105        String selection = CalendarAlerts.STATE + "=" + CalendarAlerts.FIRED;
106        mQueryHandler.startUpdate(0, null, CalendarAlerts.CONTENT_URI, values,
107                selection, null /* selectionArgs */, Utils.UNDO_DELAY);
108    }
109
110    private void dismissAlarm(long id) {
111        ContentValues values = new ContentValues(1 /* size */);
112        values.put(PROJECTION[INDEX_STATE], CalendarAlerts.DISMISSED);
113        String selection = CalendarAlerts._ID + "=" + id;
114        mQueryHandler.startUpdate(0, null, CalendarAlerts.CONTENT_URI, values,
115                selection, null /* selectionArgs */, Utils.UNDO_DELAY);
116    }
117
118    private class QueryHandler extends AsyncQueryService {
119        public QueryHandler(Context context) {
120            super(context);
121        }
122
123        @Override
124        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
125            // Only set mCursor if the Activity is not finishing. Otherwise close the cursor.
126            if (!isFinishing()) {
127                mCursor = cursor;
128                mAdapter.changeCursor(cursor);
129                mListView.setSelection(cursor.getCount() - 1);
130
131                // The results are in, enable the buttons
132                mSnoozeAllButton.setEnabled(true);
133                mDismissAllButton.setEnabled(true);
134            } else {
135                cursor.close();
136            }
137        }
138
139        @Override
140        protected void onInsertComplete(int token, Object cookie, Uri uri) {
141            if (uri != null) {
142                Long alarmTime = (Long) cookie;
143
144                if (alarmTime != 0) {
145                    // Set a new alarm to go off after the snooze delay.
146                    AlarmManager alarmManager =
147                            (AlarmManager) getSystemService(Context.ALARM_SERVICE);
148                    CalendarAlerts.scheduleAlarm(AlertActivity.this, alarmManager, alarmTime);
149                }
150            }
151        }
152
153        @Override
154        protected void onUpdateComplete(int token, Object cookie, int result) {
155            // Ignore
156        }
157    }
158
159    private static ContentValues makeContentValues(long eventId, long begin, long end,
160            long alarmTime, int minutes) {
161        ContentValues values = new ContentValues();
162        values.put(CalendarAlerts.EVENT_ID, eventId);
163        values.put(CalendarAlerts.BEGIN, begin);
164        values.put(CalendarAlerts.END, end);
165        values.put(CalendarAlerts.ALARM_TIME, alarmTime);
166        long currentTime = System.currentTimeMillis();
167        values.put(CalendarAlerts.CREATION_TIME, currentTime);
168        values.put(CalendarAlerts.RECEIVED_TIME, 0);
169        values.put(CalendarAlerts.NOTIFY_TIME, 0);
170        values.put(CalendarAlerts.STATE, CalendarAlertsColumns.SCHEDULED);
171        values.put(CalendarAlerts.MINUTES, minutes);
172        return values;
173    }
174
175    private OnItemClickListener mViewListener = new OnItemClickListener() {
176
177        public void onItemClick(AdapterView<?> parent, View view, int position,
178                long i) {
179            AlertActivity alertActivity = AlertActivity.this;
180            Cursor cursor = alertActivity.getItemForView(view);
181
182            // Mark this alarm as DISMISSED
183            dismissAlarm(cursor.getLong(INDEX_ROW_ID));
184
185            long id = cursor.getInt(AlertActivity.INDEX_EVENT_ID);
186            long startMillis = cursor.getLong(AlertActivity.INDEX_BEGIN);
187            long endMillis = cursor.getLong(AlertActivity.INDEX_END);
188            Intent eventIntent = new Intent(Intent.ACTION_VIEW);
189            Builder builder = Calendar.CONTENT_URI.buildUpon();
190            builder.appendEncodedPath("events/" + id);
191            eventIntent.setData(builder.build());
192            eventIntent.putExtra(Calendar.EVENT_BEGIN_TIME, startMillis);
193            eventIntent.putExtra(Calendar.EVENT_END_TIME, endMillis);
194            alertActivity.startActivity(eventIntent);
195
196            alertActivity.finish();
197        }
198    };
199
200    @Override
201    protected void onCreate(Bundle icicle) {
202        super.onCreate(icicle);
203
204        setContentView(R.layout.alert_activity);
205        setTitle(R.string.alert_title);
206
207        mQueryHandler = new QueryHandler(this);
208        mAdapter = new AlertAdapter(this, R.layout.alert_item);
209
210        mListView = (ListView) findViewById(R.id.alert_container);
211        mListView.setItemsCanFocus(true);
212        mListView.setAdapter(mAdapter);
213        mListView.setOnItemClickListener(mViewListener);
214
215        mSnoozeAllButton = (Button) findViewById(R.id.snooze_all);
216        mSnoozeAllButton.setOnClickListener(this);
217        mDismissAllButton = (Button) findViewById(R.id.dismiss_all);
218        mDismissAllButton.setOnClickListener(this);
219
220        // Disable the buttons, since they need mCursor, which is created asynchronously
221        mSnoozeAllButton.setEnabled(false);
222        mDismissAllButton.setEnabled(false);
223    }
224
225    @Override
226    protected void onResume() {
227        super.onResume();
228
229        // If the cursor is null, start the async handler. If it is not null just requery.
230        if (mCursor == null) {
231            Uri uri = CalendarAlerts.CONTENT_URI_BY_INSTANCE;
232            mQueryHandler.startQuery(0, null, uri, PROJECTION, SELECTION,
233                    SELECTIONARG, CalendarAlerts.DEFAULT_SORT_ORDER);
234        } else {
235            if (!mCursor.requery()) {
236                Log.w(TAG, "Cursor#requery() failed.");
237                mCursor.close();
238                mCursor = null;
239            }
240        }
241    }
242
243    @Override
244    protected void onStop() {
245        super.onStop();
246        AlertService.updateAlertNotification(this);
247
248        if (mCursor != null) {
249            mCursor.deactivate();
250        }
251    }
252
253    @Override
254    protected void onDestroy() {
255        super.onDestroy();
256        if (mCursor != null) {
257            mCursor.close();
258        }
259    }
260
261    @Override
262    public void onClick(View v) {
263        if (v == mSnoozeAllButton) {
264            long alarmTime = System.currentTimeMillis() + SNOOZE_DELAY;
265
266            NotificationManager nm =
267                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
268            nm.cancel(NOTIFICATION_ID);
269
270            if (mCursor != null) {
271                long scheduleAlarmTime = 0;
272                mCursor.moveToPosition(-1);
273                while (mCursor.moveToNext()) {
274                    long eventId = mCursor.getLong(INDEX_EVENT_ID);
275                    long begin = mCursor.getLong(INDEX_BEGIN);
276                    long end = mCursor.getLong(INDEX_END);
277
278                    // Set the "minutes" to zero to indicate this is a snoozed
279                    // alarm.  There is code in AlertService.java that checks
280                    // this field.
281                    ContentValues values =
282                            makeContentValues(eventId, begin, end, alarmTime, 0 /* minutes */);
283
284                    // Create a new alarm entry in the CalendarAlerts table
285                    if (mCursor.isLast()) {
286                        scheduleAlarmTime = alarmTime;
287                    }
288                    mQueryHandler.startInsert(0,
289                            scheduleAlarmTime, CalendarAlerts.CONTENT_URI, values,
290                            Utils.UNDO_DELAY);
291                }
292            } else {
293                Log.d(TAG, "Cursor object is null. Ignore the Snooze request.");
294            }
295
296            dismissFiredAlarms();
297            finish();
298        } else if (v == mDismissAllButton) {
299            NotificationManager nm =
300                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
301            nm.cancel(NOTIFICATION_ID);
302
303            dismissFiredAlarms();
304
305            finish();
306        }
307    }
308
309    public boolean isEmpty() {
310        return mCursor != null ? (mCursor.getCount() == 0) : true;
311    }
312
313    public Cursor getItemForView(View view) {
314        final int index = mListView.getPositionForView(view);
315        if (index < 0) {
316            return null;
317        }
318        return (Cursor) mListView.getAdapter().getItem(index);
319    }
320}
321