MailService.java revision 70edcf05387df33f4761b766add6b80999e425e9
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 android.accounts.AccountManager;
20import android.accounts.AccountManagerCallback;
21import android.accounts.AccountManagerFuture;
22import android.app.Service;
23import android.content.Context;
24import android.content.Intent;
25import android.database.Cursor;
26import android.os.Bundle;
27import android.os.IBinder;
28
29import com.android.email.SingleRunningTask;
30import com.android.email.provider.AccountReconciler;
31import com.android.email.service.EmailServiceUtils.EmailServiceInfo;
32import com.android.email2.ui.MailActivityEmail;
33import com.android.emailcommon.AccountManagerTypes;
34import com.android.emailcommon.provider.Account;
35import com.android.emailcommon.provider.HostAuth;
36import com.android.emailcommon.utility.EmailAsyncTask;
37import com.google.common.annotations.VisibleForTesting;
38
39import java.util.ArrayList;
40import java.util.List;
41
42/**
43 * Legacy service, now used mainly for account reconciliation
44 */
45public class MailService extends Service {
46
47    @Override
48    public int onStartCommand(final Intent intent, int flags, final int startId) {
49        super.onStartCommand(intent, flags, startId);
50
51        EmailAsyncTask.runAsyncParallel(new Runnable() {
52            @Override
53            public void run() {
54                reconcilePopImapAccountsSync(MailService.this);
55            }
56        });
57
58        // Make sure our services are running, if necessary
59        MailActivityEmail.setServicesEnabledAsync(this);
60
61        // Returning START_NOT_STICKY means that if a mail check is killed (e.g. due to memory
62        // pressure, there will be no explicit restart.  This is OK;  Note that we set a watchdog
63        // alarm before each mailbox check.  If the mailbox check never completes, the watchdog
64        // will fire and get things running again.
65        return START_NOT_STICKY;
66    }
67
68    @Override
69    public IBinder onBind(Intent intent) {
70        return null;
71    }
72
73    public static ArrayList<Account> getPopImapAccountList(Context context) {
74        ArrayList<Account> providerAccounts = new ArrayList<Account>();
75        Cursor c = context.getContentResolver().query(Account.CONTENT_URI, Account.ID_PROJECTION,
76                null, null, null);
77        try {
78            while (c.moveToNext()) {
79                long accountId = c.getLong(Account.CONTENT_ID_COLUMN);
80                String protocol = Account.getProtocol(context, accountId);
81                EmailServiceInfo info = EmailServiceUtils.getServiceInfo(context, protocol);
82                if ((info != null) && info.accountType.equals(AccountManagerTypes.TYPE_POP_IMAP)) {
83                    Account account = Account.restoreAccountWithId(context, accountId);
84                    if (account != null) {
85                        providerAccounts.add(account);
86                    }
87                }
88            }
89        } finally {
90            c.close();
91        }
92        return providerAccounts;
93    }
94
95    private static final SingleRunningTask<Context> sReconcilePopImapAccountsSyncExecutor =
96            new SingleRunningTask<Context>("ReconcilePopImapAccountsSync") {
97                @Override
98                protected void runInternal(Context context) {
99                    android.accounts.Account[] accountManagerAccounts = AccountManager.get(context)
100                            .getAccountsByType(AccountManagerTypes.TYPE_POP_IMAP);
101                    ArrayList<Account> providerAccounts = getPopImapAccountList(context);
102                    MailService.reconcileAccountsWithAccountManager(context, providerAccounts,
103                            accountManagerAccounts, context);
104
105                }
106    };
107
108    /**
109     * Reconcile POP/IMAP accounts.
110     */
111    public static void reconcilePopImapAccountsSync(Context context) {
112        sReconcilePopImapAccountsSyncExecutor.run(context);
113    }
114
115    /**
116     * Determines whether or not POP/IMAP accounts need reconciling or not. This is a safe operation
117     * to perform on the UI thread.
118     */
119    public static boolean hasMismatchInPopImapAccounts(Context context) {
120        android.accounts.Account[] accountManagerAccounts = AccountManager.get(context)
121                .getAccountsByType(AccountManagerTypes.TYPE_POP_IMAP);
122        ArrayList<Account> providerAccounts = getPopImapAccountList(context);
123        return AccountReconciler.accountsNeedReconciling(
124                context, providerAccounts, accountManagerAccounts);
125    }
126
127    /**
128     * See Utility.reconcileAccounts for details
129     * @param context The context in which to operate
130     * @param emailProviderAccounts the exchange provider accounts to work from
131     * @param accountManagerAccounts The account manager accounts to work from
132     * @param providerContext the provider's context (in unit tests, this may differ from context)
133     */
134    @VisibleForTesting
135    public static void reconcileAccountsWithAccountManager(Context context,
136            List<Account> emailProviderAccounts, android.accounts.Account[] accountManagerAccounts,
137            Context providerContext) {
138        AccountReconciler.reconcileAccounts(context, emailProviderAccounts, accountManagerAccounts,
139                providerContext);
140    }
141
142    public static AccountManagerFuture<Bundle> setupAccountManagerAccount(Context context,
143            Account account, boolean email, boolean calendar, boolean contacts,
144            AccountManagerCallback<Bundle> callback) {
145        Bundle options = new Bundle();
146        HostAuth hostAuthRecv = HostAuth.restoreHostAuthWithId(context, account.mHostAuthKeyRecv);
147        if (hostAuthRecv == null) {
148            return null;
149        }
150        // Set up username/password
151        options.putString(EasAuthenticatorService.OPTIONS_USERNAME, account.mEmailAddress);
152        options.putString(EasAuthenticatorService.OPTIONS_PASSWORD, hostAuthRecv.mPassword);
153        options.putBoolean(EasAuthenticatorService.OPTIONS_CONTACTS_SYNC_ENABLED, contacts);
154        options.putBoolean(EasAuthenticatorService.OPTIONS_CALENDAR_SYNC_ENABLED, calendar);
155        options.putBoolean(EasAuthenticatorService.OPTIONS_EMAIL_SYNC_ENABLED, email);
156        EmailServiceInfo info = EmailServiceUtils.getServiceInfo(context, hostAuthRecv.mProtocol);
157        return AccountManager.get(context).addAccount(info.accountType, null, null, options, null,
158                callback, null);
159    }
160}
161