EmailBroadcastProcessorService.java revision c6089bc01f2ae49fb11904a4b4f222811358254f
1/*
2 * Copyright (C) 2010 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.app.IntentService;
21import android.content.ComponentName;
22import android.content.ContentResolver;
23import android.content.ContentUris;
24import android.content.ContentValues;
25import android.content.Context;
26import android.content.Intent;
27import android.content.pm.PackageManager;
28import android.database.Cursor;
29import android.net.Uri;
30import android.util.Log;
31
32import com.android.email.NotificationController;
33import com.android.email.Preferences;
34import com.android.email.SecurityPolicy;
35import com.android.email.activity.setup.AccountSettings;
36import com.android.emailcommon.Logging;
37import com.android.emailcommon.VendorPolicyLoader;
38import com.android.emailcommon.provider.Account;
39import com.android.emailcommon.provider.EmailContent.AccountColumns;
40import com.android.emailcommon.provider.HostAuth;
41
42/**
43 * The service that really handles broadcast intents on a worker thread.
44 *
45 * We make it a service, because:
46 * <ul>
47 *   <li>So that it's less likely for the process to get killed.
48 *   <li>Even if it does, the Intent that have started it will be re-delivered by the system,
49 *   and we can start the process again.  (Using {@link #setIntentRedelivery}).
50 * </ul>
51 *
52 * This also handles the DeviceAdminReceiver in SecurityPolicy, because it is also
53 * a BroadcastReceiver and requires the same processing semantics.
54 */
55public class EmailBroadcastProcessorService extends IntentService {
56    // Action used for BroadcastReceiver entry point
57    private static final String ACTION_BROADCAST = "broadcast_receiver";
58
59    // Dialing "*#*#36245#*#*" to open the debug screen.   "36245" = "email"
60    private static final String ACTION_SECRET_CODE = "android.provider.Telephony.SECRET_CODE";
61    private static final String SECRET_CODE_HOST_DEBUG_SCREEN = "36245";
62
63    // This is a helper used to process DeviceAdminReceiver messages
64    private static final String ACTION_DEVICE_POLICY_ADMIN = "com.android.email.devicepolicy";
65    private static final String EXTRA_DEVICE_POLICY_ADMIN = "message_code";
66
67    // Broadcast received to initiate new message notification updates
68    public static final String ACTION_NOTIFY_NEW_MAIL =
69            "com.android.mail.action.update_notification";
70
71    public EmailBroadcastProcessorService() {
72        // Class name will be the thread name.
73        super(EmailBroadcastProcessorService.class.getName());
74
75        // Intent should be redelivered if the process gets killed before completing the job.
76        setIntentRedelivery(true);
77    }
78
79    /**
80     * Entry point for {@link EmailBroadcastReceiver}.
81     */
82    public static void processBroadcastIntent(Context context, Intent broadcastIntent) {
83        Intent i = new Intent(context, EmailBroadcastProcessorService.class);
84        i.setAction(ACTION_BROADCAST);
85        i.putExtra(Intent.EXTRA_INTENT, broadcastIntent);
86        context.startService(i);
87    }
88
89    /**
90     * Entry point for {@link com.android.email.SecurityPolicy.PolicyAdmin}.  These will
91     * simply callback to {@link
92     * com.android.email.SecurityPolicy#onDeviceAdminReceiverMessage(Context, int)}.
93     */
94    public static void processDevicePolicyMessage(Context context, int message) {
95        Intent i = new Intent(context, EmailBroadcastProcessorService.class);
96        i.setAction(ACTION_DEVICE_POLICY_ADMIN);
97        i.putExtra(EXTRA_DEVICE_POLICY_ADMIN, message);
98        context.startService(i);
99    }
100
101    @Override
102    protected void onHandleIntent(Intent intent) {
103        // This method is called on a worker thread.
104
105        // Dispatch from entry point
106        final String action = intent.getAction();
107        if (ACTION_BROADCAST.equals(action)) {
108            final Intent broadcastIntent = intent.getParcelableExtra(Intent.EXTRA_INTENT);
109            final String broadcastAction = broadcastIntent.getAction();
110
111            if (Intent.ACTION_BOOT_COMPLETED.equals(broadcastAction)) {
112                onBootCompleted();
113            } else if (ACTION_SECRET_CODE.equals(broadcastAction)
114                    && SECRET_CODE_HOST_DEBUG_SCREEN.equals(broadcastIntent.getData().getHost())) {
115                AccountSettings.actionSettingsWithDebug(this);
116            } else if (AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION.equals(broadcastAction)) {
117                onSystemAccountChanged();
118            } else if (ACTION_NOTIFY_NEW_MAIL.equals(broadcastAction)) {
119                NotificationController.notifyNewMail(this, broadcastIntent);
120            }
121        } else if (ACTION_DEVICE_POLICY_ADMIN.equals(action)) {
122            int message = intent.getIntExtra(EXTRA_DEVICE_POLICY_ADMIN, -1);
123            SecurityPolicy.onDeviceAdminReceiverMessage(this, message);
124        }
125    }
126
127    /**
128     * Handles {@link Intent#ACTION_BOOT_COMPLETED}.  Called on a worker thread.
129     */
130    private void onBootCompleted() {
131        performOneTimeInitialization();
132
133        // Starts remote services, if any
134        EmailServiceUtils.startRemoteServices(this);
135    }
136
137    private void performOneTimeInitialization() {
138        final Preferences pref = Preferences.getPreferences(this);
139        int progress = pref.getOneTimeInitializationProgress();
140        final int initialProgress = progress;
141
142        if (progress < 1) {
143            Log.i(Logging.LOG_TAG, "Onetime initialization: 1");
144            progress = 1;
145            if (VendorPolicyLoader.getInstance(this).useAlternateExchangeStrings()) {
146                setComponentEnabled(EasAuthenticatorServiceAlternate.class, true);
147                setComponentEnabled(EasAuthenticatorService.class, false);
148            }
149        }
150
151        if (progress < 2) {
152            Log.i(Logging.LOG_TAG, "Onetime initialization: 2");
153            progress = 2;
154            setImapDeletePolicy(this);
155        }
156
157        // Add your initialization steps here.
158        // Use "progress" to skip the initializations that's already done before.
159        // Using this preference also makes it safe when a user skips an upgrade.  (i.e. upgrading
160        // version N to version N+2)
161
162        if (progress != initialProgress) {
163            pref.setOneTimeInitializationProgress(progress);
164            Log.i(Logging.LOG_TAG, "Onetime initialization: completed.");
165        }
166    }
167
168    /**
169     * Sets the delete policy to the correct value for all IMAP accounts. This will have no
170     * effect on either EAS or POP3 accounts.
171     */
172    /*package*/ static void setImapDeletePolicy(Context context) {
173        ContentResolver resolver = context.getContentResolver();
174        Cursor c = resolver.query(Account.CONTENT_URI, Account.CONTENT_PROJECTION,
175                null, null, null);
176        try {
177            while (c.moveToNext()) {
178                long recvAuthKey = c.getLong(Account.CONTENT_HOST_AUTH_KEY_RECV_COLUMN);
179                HostAuth recvAuth = HostAuth.restoreHostAuthWithId(context, recvAuthKey);
180                if (HostAuth.LEGACY_SCHEME_IMAP.equals(recvAuth.mProtocol)) {
181                    int flags = c.getInt(Account.CONTENT_FLAGS_COLUMN);
182                    flags &= ~Account.FLAGS_DELETE_POLICY_MASK;
183                    flags |= Account.DELETE_POLICY_ON_DELETE << Account.FLAGS_DELETE_POLICY_SHIFT;
184                    ContentValues cv = new ContentValues();
185                    cv.put(AccountColumns.FLAGS, flags);
186                    long accountId = c.getLong(Account.CONTENT_ID_COLUMN);
187                    Uri uri = ContentUris.withAppendedId(Account.CONTENT_URI, accountId);
188                    resolver.update(uri, cv, null, null);
189                }
190            }
191        } finally {
192            c.close();
193        }
194    }
195
196    private void setComponentEnabled(Class<?> clazz, boolean enabled) {
197        final ComponentName c = new ComponentName(this, clazz.getName());
198        getPackageManager().setComponentEnabledSetting(c,
199                enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
200                        : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
201                PackageManager.DONT_KILL_APP);
202    }
203
204    private void onSystemAccountChanged() {
205        Log.i(Logging.LOG_TAG, "System accounts updated.");
206        MailService.reconcilePopImapAccountsSync(this);
207
208        // Start any remote services
209        EmailServiceUtils.startRemoteServices(this);
210    }
211}
212