AlertActivity.java revision db4ce4a81063b7f5f6068f4144f8a3e3bca1e064
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.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
130                // The results are in, enable the buttons
131                mSnoozeAllButton.setEnabled(true);
132                mDismissAllButton.setEnabled(true);
133            } else {
134                cursor.close();
135            }
136        }
137
138        @Override
139        protected void onInsertComplete(int token, Object cookie, Uri uri) {
140            if (uri != null) {
141                Long alarmTime = (Long) cookie;
142
143                if (alarmTime != 0) {
144                    // Set a new alarm to go off after the snooze delay.
145                    AlarmManager alarmManager =
146                            (AlarmManager) getSystemService(Context.ALARM_SERVICE);
147                    CalendarAlerts.scheduleAlarm(AlertActivity.this, alarmManager, alarmTime);
148                }
149            }
150        }
151
152        @Override
153        protected void onUpdateComplete(int token, Object cookie, int result) {
154            // Ignore
155        }
156    }
157
158    private static ContentValues makeContentValues(long eventId, long begin, long end,
159            long alarmTime, int minutes) {
160        ContentValues values = new ContentValues();
161        values.put(CalendarAlerts.EVENT_ID, eventId);
162        values.put(CalendarAlerts.BEGIN, begin);
163        values.put(CalendarAlerts.END, end);
164        values.put(CalendarAlerts.ALARM_TIME, alarmTime);
165        long currentTime = System.currentTimeMillis();
166        values.put(CalendarAlerts.CREATION_TIME, currentTime);
167        values.put(CalendarAlerts.RECEIVED_TIME, 0);
168        values.put(CalendarAlerts.NOTIFY_TIME, 0);
169        values.put(CalendarAlerts.STATE, CalendarAlertsColumns.SCHEDULED);
170        values.put(CalendarAlerts.MINUTES, minutes);
171        return values;
172    }
173
174    private OnItemClickListener mViewListener = new OnItemClickListener() {
175
176        public void onItemClick(AdapterView<?> parent, View view, int position,
177                long i) {
178            AlertActivity alertActivity = AlertActivity.this;
179            Cursor cursor = alertActivity.getItemForView(view);
180
181            // Mark this alarm as DISMISSED
182            dismissAlarm(cursor.getLong(INDEX_ROW_ID));
183
184            long id = cursor.getInt(AlertActivity.INDEX_EVENT_ID);
185            long startMillis = cursor.getLong(AlertActivity.INDEX_BEGIN);
186            long endMillis = cursor.getLong(AlertActivity.INDEX_END);
187            Intent eventIntent = new Intent(Intent.ACTION_VIEW);
188            Builder builder = Calendar.CONTENT_URI.buildUpon();
189            builder.appendEncodedPath("time/" + startMillis);
190            eventIntent.setData(builder.build());
191            alertActivity.startActivity(eventIntent);
192
193            alertActivity.finish();
194        }
195    };
196
197    @Override
198    protected void onCreate(Bundle icicle) {
199        super.onCreate(icicle);
200
201        setContentView(R.layout.alert_activity);
202        setTitle(R.string.alert_title);
203
204        WindowManager.LayoutParams lp = getWindow().getAttributes();
205        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
206        lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
207
208        getWindow().setAttributes(lp);
209
210        mQueryHandler = new QueryHandler(this);
211        mAdapter = new AlertAdapter(this, R.layout.alert_item);
212
213        mListView = (ListView) findViewById(R.id.alert_container);
214        mListView.setItemsCanFocus(true);
215        mListView.setAdapter(mAdapter);
216        mListView.setOnItemClickListener(mViewListener);
217
218        mSnoozeAllButton = (Button) findViewById(R.id.snooze_all);
219        mSnoozeAllButton.setOnClickListener(this);
220        mDismissAllButton = (Button) findViewById(R.id.dismiss_all);
221        mDismissAllButton.setOnClickListener(this);
222
223        // Disable the buttons, since they need mCursor, which is created asynchronously
224        mSnoozeAllButton.setEnabled(false);
225        mDismissAllButton.setEnabled(false);
226    }
227
228    @Override
229    protected void onResume() {
230        super.onResume();
231
232        // If the cursor is null, start the async handler. If it is not null just requery.
233        if (mCursor == null) {
234            Uri uri = CalendarAlerts.CONTENT_URI_BY_INSTANCE;
235            mQueryHandler.startQuery(0, null, uri, PROJECTION, SELECTION,
236                    SELECTIONARG, CalendarAlerts.DEFAULT_SORT_ORDER);
237        } else {
238            if (!mCursor.requery()) {
239                Log.w(TAG, "Cursor#requery() failed.");
240                mCursor.close();
241                mCursor = null;
242            }
243        }
244    }
245
246    @Override
247    protected void onStop() {
248        super.onStop();
249        AlertService.updateAlertNotification(this);
250
251        if (mCursor != null) {
252            mCursor.deactivate();
253        }
254    }
255
256    @Override
257    protected void onDestroy() {
258        super.onDestroy();
259        if (mCursor != null) {
260            mCursor.close();
261        }
262    }
263
264    @Override
265    public void onClick(View v) {
266        if (v == mSnoozeAllButton) {
267            long alarmTime = System.currentTimeMillis() + SNOOZE_DELAY;
268
269            NotificationManager nm =
270                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
271            nm.cancel(NOTIFICATION_ID);
272
273            if (mCursor != null) {
274                long scheduleAlarmTime = 0;
275                mCursor.moveToPosition(-1);
276                while (mCursor.moveToNext()) {
277                    long eventId = mCursor.getLong(INDEX_EVENT_ID);
278                    long begin = mCursor.getLong(INDEX_BEGIN);
279                    long end = mCursor.getLong(INDEX_END);
280
281                    // Set the "minutes" to zero to indicate this is a snoozed
282                    // alarm.  There is code in AlertService.java that checks
283                    // this field.
284                    ContentValues values =
285                            makeContentValues(eventId, begin, end, alarmTime, 0 /* minutes */);
286
287                    // Create a new alarm entry in the CalendarAlerts table
288                    if (mCursor.isLast()) {
289                        scheduleAlarmTime = alarmTime;
290                    }
291                    mQueryHandler.startInsert(0,
292                            scheduleAlarmTime, CalendarAlerts.CONTENT_URI, values,
293                            Utils.UNDO_DELAY);
294                }
295            } else {
296                Log.d(TAG, "Cursor object is null. Ignore the Snooze request.");
297            }
298
299            dismissFiredAlarms();
300            finish();
301        } else if (v == mDismissAllButton) {
302            NotificationManager nm =
303                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
304            nm.cancel(NOTIFICATION_ID);
305
306            dismissFiredAlarms();
307
308            finish();
309        }
310    }
311
312    public boolean isEmpty() {
313        return mCursor != null ? (mCursor.getCount() == 0) : true;
314    }
315
316    public Cursor getItemForView(View view) {
317        final int index = mListView.getPositionForView(view);
318        if (index < 0) {
319            return null;
320        }
321        return (Cursor) mListView.getAdapter().getItem(index);
322    }
323}
324