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