MailService.java revision c0c9c33322deecace00a32766e0a1b355aad4b31
1/*
2 * Copyright (C) 2008 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.email.service;
18
19import com.android.email.Controller;
20import com.android.email.Email;
21import com.android.email.R;
22import com.android.email.activity.MessageList;
23import com.android.email.mail.MessagingException;
24import com.android.email.provider.EmailContent.Account;
25import com.android.email.provider.EmailContent.AccountColumns;
26import com.android.email.provider.EmailContent.Mailbox;
27
28import android.app.AlarmManager;
29import android.app.Notification;
30import android.app.NotificationManager;
31import android.app.PendingIntent;
32import android.app.Service;
33import android.content.ContentUris;
34import android.content.ContentValues;
35import android.content.Context;
36import android.content.Intent;
37import android.database.Cursor;
38import android.net.Uri;
39import android.os.IBinder;
40import android.os.SystemClock;
41import android.util.Config;
42import android.util.Log;
43
44import java.util.HashMap;
45
46/**
47 * Background service for refreshing non-push email accounts.
48 */
49public class MailService extends Service {
50    /** DO NOT CHECK IN "TRUE" */
51    private static final boolean DEBUG_FORCE_QUICK_REFRESH = false;        // force 1-minute refresh
52
53    public static int NEW_MESSAGE_NOTIFICATION_ID = 1;
54
55    private static final String ACTION_CHECK_MAIL =
56        "com.android.email.intent.action.MAIL_SERVICE_WAKEUP";
57    private static final String ACTION_RESCHEDULE =
58        "com.android.email.intent.action.MAIL_SERVICE_RESCHEDULE";
59    private static final String ACTION_CANCEL =
60        "com.android.email.intent.action.MAIL_SERVICE_CANCEL";
61    private static final String ACTION_NOTIFY_MAIL =
62        "com.android.email.intent.action.MAIL_SERVICE_NOTIFY";
63
64    private static final String EXTRA_CHECK_ACCOUNT = "com.android.email.intent.extra.ACCOUNT";
65    private static final String EXTRA_ACCOUNT_INFO = "com.android.email.intent.extra.ACCOUNT_INFO";
66
67    private static final String[] NEW_MESSAGE_COUNT_PROJECTION =
68        new String[] {AccountColumns.NEW_MESSAGE_COUNT};
69
70    private Controller.Result mControllerCallback = new ControllerResults();
71
72    private int mStartId;
73
74    /**
75     * Access must be synchronized, because there are accesses from the Controller callback
76     */
77    private static HashMap<Long,AccountSyncReport> mSyncReports =
78        new HashMap<Long,AccountSyncReport>();
79
80    /**
81     * Simple template used for clearing new message count in accounts
82     */
83    static ContentValues mClearNewMessages;
84    static {
85        mClearNewMessages = new ContentValues();
86        mClearNewMessages.put(Account.NEW_MESSAGE_COUNT, 0);
87    }
88
89    public static void actionReschedule(Context context) {
90        Intent i = new Intent();
91        i.setClass(context, MailService.class);
92        i.setAction(MailService.ACTION_RESCHEDULE);
93        context.startService(i);
94    }
95
96    public static void actionCancel(Context context)  {
97        Intent i = new Intent();
98        i.setClass(context, MailService.class);
99        i.setAction(MailService.ACTION_CANCEL);
100        context.startService(i);
101    }
102
103    /**
104     * Reset new message counts for one or all accounts.  This clears both our local copy and
105     * the values (if any) stored in the account records.
106     *
107     * @param accountId account to clear, or -1 for all accounts
108     */
109    public static void resetNewMessageCount(Context context, long accountId) {
110        synchronized (mSyncReports) {
111            for (AccountSyncReport report : mSyncReports.values()) {
112                if (accountId == -1 || accountId == report.accountId) {
113                    report.numNewMessages = 0;
114                }
115            }
116        }
117        // now do the database - all accounts, or just one of them
118        Uri uri;
119        if (accountId == -1) {
120            uri = Account.CONTENT_URI;
121        } else {
122            uri = ContentUris.withAppendedId(Account.CONTENT_URI, accountId);
123        }
124        context.getContentResolver().update(uri, mClearNewMessages, null, null);
125    }
126
127    /**
128     * Entry point for asynchronous message services (e.g. push mode) to post notifications of new
129     * messages.  This assumes that the push provider has already synced the messages into the
130     * appropriate database - this simply triggers the notification mechanism.
131     *
132     * @param context a context
133     * @param accountId the id of the account that is reporting new messages
134     * @param newCount the number of new messages
135     */
136    public static void actionNotifyNewMessages(Context context, long accountId) {
137        Intent i = new Intent(ACTION_NOTIFY_MAIL);
138        i.setClass(context, MailService.class);
139        i.putExtra(EXTRA_CHECK_ACCOUNT, accountId);
140        context.startService(i);
141    }
142
143    @Override
144    public void onStart(Intent intent, int startId) {
145        super.onStart(intent, startId);
146
147        // TODO this needs to be passed through the controller and back to us
148        this.mStartId = startId;
149        String action = intent.getAction();
150
151        Controller controller = Controller.getInstance(getApplication());
152        controller.addResultCallback(mControllerCallback);
153
154        if (ACTION_CHECK_MAIL.equals(action)) {
155            if (Config.LOGD && Email.DEBUG) {
156                Log.d(Email.LOG_TAG, "*** MailService: checking mail");
157            }
158            // If we have the data, restore the last-sync-times for each account
159            // These are cached in the wakeup intent in case the process was killed.
160            restoreSyncReports(intent);
161
162            // Sync a specific account if given
163            long checkAccountId = intent.getLongExtra(EXTRA_CHECK_ACCOUNT, -1);
164            if (checkAccountId != -1) {
165                // launch an account sync in the controller
166                syncOneAccount(controller, checkAccountId, startId);
167            } else {
168                // Find next account to sync, and reschedule
169                AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
170                reschedule(alarmManager);
171                stopSelf(startId);
172            }
173        }
174        else if (ACTION_CANCEL.equals(action)) {
175            if (Config.LOGD && Email.DEBUG) {
176                Log.d(Email.LOG_TAG, "*** MailService: cancel");
177            }
178            cancel();
179            stopSelf(startId);
180        }
181        else if (ACTION_RESCHEDULE.equals(action)) {
182            if (Config.LOGD && Email.DEBUG) {
183                Log.d(Email.LOG_TAG, "*** MailService: reschedule");
184            }
185            AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
186            reschedule(alarmManager);
187            stopSelf(startId);
188        } else if (ACTION_NOTIFY_MAIL.equals(action)) {
189            long accountId = intent.getLongExtra(EXTRA_CHECK_ACCOUNT, -1);
190            // Get the current new message count
191            Cursor c = getContentResolver().query(
192                    ContentUris.withAppendedId(Account.CONTENT_URI, accountId),
193                    NEW_MESSAGE_COUNT_PROJECTION, null, null, null);
194            int newMessageCount = 0;
195            try {
196                if (c.moveToFirst()) {
197                    newMessageCount = c.getInt(0);
198                } else {
199                    // If the account no longer exists, set to -1 (which is handled below)
200                    accountId = -1;
201                }
202            } finally {
203                c.close();
204            }
205            if (Config.LOGD && Email.DEBUG) {
206                Log.d(Email.LOG_TAG, "*** MailService: notify accountId=" + Long.toString(accountId)
207                        + " count=" + newMessageCount);
208            }
209            if (accountId != -1) {
210                updateAccountReport(accountId, newMessageCount);
211                notifyNewMessages(accountId);
212            }
213            stopSelf(startId);
214        }
215    }
216
217    @Override
218    public IBinder onBind(Intent intent) {
219        return null;
220    }
221
222    @Override
223    public void onDestroy() {
224        super.onDestroy();
225        Controller.getInstance(getApplication()).removeResultCallback(mControllerCallback);
226    }
227
228    private void cancel() {
229        AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
230        PendingIntent pi = createAlarmIntent(-1, null);
231        alarmMgr.cancel(pi);
232    }
233
234    /**
235     * Create and send an alarm with the entire list.  This also sends a list of known last-sync
236     * times with the alarm, so if we are killed between alarms, we don't lose this info.
237     *
238     * @param alarmMgr passed in so we can mock for testing.
239     */
240    /* package */ void reschedule(AlarmManager alarmMgr) {
241        // restore the reports if lost
242        setupSyncReports(-1);
243        synchronized (mSyncReports) {
244            int numAccounts = mSyncReports.size();
245            long[] accountInfo = new long[numAccounts * 2];     // pairs of { accountId, lastSync }
246            int accountInfoIndex = 0;
247
248            long nextCheckTime = Long.MAX_VALUE;
249            AccountSyncReport nextAccount = null;
250            long timeNow = SystemClock.elapsedRealtime();
251
252            for (AccountSyncReport report : mSyncReports.values()) {
253                if (report.syncInterval <= 0) {                         // no timed checks - skip
254                    continue;
255                }
256                // select next account to sync
257                if ((report.prevSyncTime == 0)                          // never checked
258                        || (report.nextSyncTime < timeNow)) {           // overdue
259                    nextCheckTime = 0;
260                    nextAccount = report;
261                } else if (report.nextSyncTime < nextCheckTime) {       // next to be checked
262                    nextCheckTime = report.nextSyncTime;
263                    nextAccount = report;
264                }
265                // collect last-sync-times for all accounts
266                // this is using pairs of {long,long} to simplify passing in a bundle
267                accountInfo[accountInfoIndex++] = report.accountId;
268                accountInfo[accountInfoIndex++] = report.prevSyncTime;
269            }
270
271            // set/clear alarm as needed
272            long idToCheck = (nextAccount == null) ? -1 : nextAccount.accountId;
273            PendingIntent pi = createAlarmIntent(idToCheck, accountInfo);
274
275            if (nextAccount == null) {
276                alarmMgr.cancel(pi);
277                Log.d(Email.LOG_TAG, "alarm cancel - no account to check");
278            } else {
279                alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextCheckTime, pi);
280                Log.d(Email.LOG_TAG, "alarm set at " + nextCheckTime + " for " + nextAccount);
281            }
282        }
283    }
284
285    /**
286     * Return a pending intent for use by this alarm.  Most of the fields must be the same
287     * (in order for the intent to be recognized by the alarm manager) but the extras can
288     * be different, and are passed in here as parameters.
289     */
290    /* package */ PendingIntent createAlarmIntent(long checkId, long[] accountInfo) {
291        Intent i = new Intent();
292        i.setClassName("com.android.email", "com.android.email.service.MailService");
293        i.setAction(ACTION_CHECK_MAIL);
294        i.putExtra(EXTRA_CHECK_ACCOUNT, checkId);
295        i.putExtra(EXTRA_ACCOUNT_INFO, accountInfo);
296        PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
297        return pi;
298    }
299
300    /**
301     * Start a controller sync for a specific account
302     */
303    private void syncOneAccount(Controller controller, long checkAccountId, int startId) {
304        long inboxId = Mailbox.findMailboxOfType(this, checkAccountId, Mailbox.TYPE_INBOX);
305        if (inboxId == Mailbox.NO_MAILBOX) {
306            // no inbox??  sync mailboxes
307        } else {
308            controller.serviceCheckMail(checkAccountId, inboxId, startId, mControllerCallback);
309        }
310    }
311
312    /**
313     * Note:  Times are relative to SystemClock.elapsedRealtime()
314     */
315    private static class AccountSyncReport {
316        long accountId;
317        long prevSyncTime;      // 0 == unknown
318        long nextSyncTime;      // 0 == ASAP  -1 == don't sync
319        int numNewMessages;
320
321        int syncInterval;
322        boolean notify;
323        boolean vibrate;
324        Uri ringtoneUri;
325
326        String displayName;     // temporary, for debug logging
327
328
329        @Override
330        public String toString() {
331            return displayName + ": prevSync=" + prevSyncTime + " nextSync=" + nextSyncTime
332                    + " numNew=" + numNewMessages;
333        }
334    }
335
336    /**
337     * scan accounts to create a list of { acct, prev sync, next sync, #new }
338     * use this to create a fresh copy.  assumes all accounts need sync
339     *
340     * @param accountId -1 will rebuild the list if empty.  other values will force loading
341     *   of a single account (e.g if it was created after the original list population)
342     */
343    /* package */ void setupSyncReports(long accountId) {
344        synchronized (mSyncReports) {
345            if (accountId == -1) {
346                // -1 == reload the list if empty, otherwise exit immediately
347                if (mSyncReports.size() > 0) {
348                    return;
349                }
350            } else {
351                // load a single account if it doesn't already have a sync record
352                if (mSyncReports.containsKey(accountId)) {
353                    return;
354                }
355            }
356
357            // setup to add a single account or all accounts
358            Uri uri;
359            if (accountId == -1) {
360                uri = Account.CONTENT_URI;
361            } else {
362                uri = ContentUris.withAppendedId(Account.CONTENT_URI, accountId);
363            }
364
365            // TODO use a narrower projection here
366            Cursor c = getContentResolver().query(uri, Account.CONTENT_PROJECTION,
367                    null, null, null);
368            try {
369                while (c.moveToNext()) {
370                    AccountSyncReport report = new AccountSyncReport();
371                    int syncInterval = c.getInt(Account.CONTENT_SYNC_INTERVAL_COLUMN);
372                    int flags = c.getInt(Account.CONTENT_FLAGS_COLUMN);
373                    String ringtoneString = c.getString(Account.CONTENT_RINGTONE_URI_COLUMN);
374
375                    // For debugging only
376                    if (DEBUG_FORCE_QUICK_REFRESH && syncInterval >= 0) {
377                        syncInterval = 1;
378                    }
379
380                    report.accountId = c.getLong(Account.CONTENT_ID_COLUMN);
381                    report.prevSyncTime = 0;
382                    report.nextSyncTime = (syncInterval > 0) ? 0 : -1;  // 0 == ASAP -1 == no sync
383                    report.numNewMessages = 0;
384
385                    report.syncInterval = syncInterval;
386                    report.notify = (flags & Account.FLAGS_NOTIFY_NEW_MAIL) != 0;
387                    report.vibrate = (flags & Account.FLAGS_VIBRATE) != 0;
388                    report.ringtoneUri = (ringtoneString == null) ? null
389                                                                  : Uri.parse(ringtoneString);
390
391                    report.displayName = c.getString(Account.CONTENT_DISPLAY_NAME_COLUMN);
392
393                    // TODO lookup # new in inbox
394                    mSyncReports.put(report.accountId, report);
395                }
396            } finally {
397                c.close();
398            }
399        }
400    }
401
402    /**
403     * Update list with a single account's sync times and unread count
404     *
405     * @param accountId the account being udpated
406     * @param newCount the number of new messages, or -1 if not being reported (don't update)
407     * @return the report for the updated account, or null if it doesn't exist (e.g. deleted)
408     */
409    /* package */ AccountSyncReport updateAccountReport(long accountId, int newCount) {
410        // restore the reports if lost
411        setupSyncReports(accountId);
412        synchronized (mSyncReports) {
413            AccountSyncReport report = mSyncReports.get(accountId);
414            if (report == null) {
415                // discard result - there is no longer an account with this id
416                Log.d(Email.LOG_TAG, "No account to update for id=" + Long.toString(accountId));
417                return null;
418            }
419
420            // report found - update it (note - editing the report while in-place in the hashmap)
421            report.prevSyncTime = SystemClock.elapsedRealtime();
422            if (report.syncInterval > 0) {
423                report.nextSyncTime = report.prevSyncTime + (report.syncInterval * 1000 * 60);
424            }
425            if (newCount != -1) {
426                report.numNewMessages = newCount;
427            }
428            Log.d(Email.LOG_TAG, "update account " + report.toString());
429            return report;
430        }
431    }
432
433    /**
434     * when we receive an alarm, update the account sync reports list if necessary
435     * this will be the case when if we have restarted the process and lost the data
436     * in the global.
437     *
438     * @param restoreIntent the intent with the list
439     */
440    /* package */ void restoreSyncReports(Intent restoreIntent) {
441        // restore the reports if lost
442        setupSyncReports(-1);
443        synchronized (mSyncReports) {
444            long[] accountInfo = restoreIntent.getLongArrayExtra(EXTRA_ACCOUNT_INFO);
445            if (accountInfo == null) {
446                Log.d(Email.LOG_TAG, "no data in intent to restore");
447                return;
448            }
449            int accountInfoIndex = 0;
450            int accountInfoLimit = accountInfo.length;
451            while (accountInfoIndex < accountInfoLimit) {
452                long accountId = accountInfo[accountInfoIndex++];
453                long prevSync = accountInfo[accountInfoIndex++];
454                AccountSyncReport report = mSyncReports.get(accountId);
455                if (report != null) {
456                    if (report.prevSyncTime == 0) {
457                        report.prevSyncTime = prevSync;
458                        Log.d(Email.LOG_TAG, "restore prev sync for account" + report);
459                    }
460                }
461            }
462        }
463    }
464
465    class ControllerResults implements Controller.Result {
466
467        public void loadAttachmentCallback(MessagingException result, long messageId,
468                long attachmentId, int progress) {
469        }
470
471        public void updateMailboxCallback(MessagingException result, long accountId,
472                long mailboxId, int progress, int numNewMessages) {
473            if (result == null) {
474                updateAccountReport(accountId, numNewMessages);
475                if (numNewMessages > 0) {
476                    notifyNewMessages(accountId);
477                }
478            } else {
479                updateAccountReport(accountId, -1);
480            }
481        }
482
483        public void updateMailboxListCallback(MessagingException result, long accountId,
484                int progress) {
485        }
486
487        public void serviceCheckMailCallback(MessagingException result, long accountId,
488                long mailboxId, int progress, long tag) {
489            if (progress == 100) {
490                AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
491                reschedule(alarmManager);
492                int serviceId = MailService.this.mStartId;
493                if (tag != 0) {
494                    serviceId = (int) tag;
495                }
496                stopSelf(serviceId);
497            }
498        }
499    }
500
501    /**
502     * Prepare notifications for a given new account having received mail
503     * The notification is organized around the account that has the new mail (e.g. selecting
504     * the alert preferences) but the notification will include a summary if other
505     * accounts also have new mail.
506     */
507    private void notifyNewMessages(long accountId) {
508        boolean notify = false;
509        boolean vibrate = false;
510        Uri ringtone = null;
511        int accountsWithNewMessages = 0;
512        int numNewMessages = 0;
513        String reportName = null;
514        synchronized (mSyncReports) {
515            for (AccountSyncReport report : mSyncReports.values()) {
516                if (report.numNewMessages == 0) {
517                    continue;
518                }
519                numNewMessages += report.numNewMessages;
520                accountsWithNewMessages += 1;
521                if (report.accountId == accountId) {
522                    notify = report.notify;
523                    vibrate = report.vibrate;
524                    ringtone = report.ringtoneUri;
525                    reportName = report.displayName;
526                }
527            }
528        }
529        if (!notify) {
530            return;
531        }
532
533        // set up to post a notification
534        Intent intent;
535        String reportString;
536
537        if (accountsWithNewMessages == 1) {
538            // Prepare a report for a single account
539            // "12 unread (gmail)"
540            reportString = getResources().getQuantityString(
541                    R.plurals.notification_new_one_account_fmt, numNewMessages,
542                    numNewMessages, reportName);
543            intent = MessageList.actionHandleAccountIntent(this,
544                    accountId, -1, Mailbox.TYPE_INBOX);
545        } else {
546            // Prepare a report for multiple accounts
547            // "4 accounts"
548            reportString = getResources().getQuantityString(
549                    R.plurals.notification_new_multi_account_fmt, accountsWithNewMessages,
550                    accountsWithNewMessages);
551            intent = MessageList.actionHandleAccountIntent(this,
552                    -1, MessageList.QUERY_ALL_INBOXES, -1);
553        }
554
555        // prepare appropriate pending intent, set up notification, and send
556        PendingIntent pending = PendingIntent.getActivity(this, 0, intent, 0);
557
558        Notification notification = new Notification(
559                R.drawable.stat_notify_email_generic,
560                getString(R.string.notification_new_title),
561                System.currentTimeMillis());
562        notification.setLatestEventInfo(this,
563                getString(R.string.notification_new_title),
564                reportString,
565                pending);
566
567        notification.sound = ringtone;
568        notification.defaults = vibrate
569            ? Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE
570            : Notification.DEFAULT_LIGHTS;
571
572        NotificationManager notificationManager =
573            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
574        notificationManager.notify(NEW_MESSAGE_NOTIFICATION_ID, notification);
575    }
576}
577