EmailActivity.java revision 37c8a70d644ffc91a880f67a80a8558b4c53d5c3
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.activity;
18
19import android.app.Activity;
20import android.app.AlertDialog;
21import android.app.Dialog;
22import android.app.Fragment;
23import android.content.ContentUris;
24import android.content.ContentValues;
25import android.content.DialogInterface;
26import android.content.Intent;
27import android.os.Bundle;
28import android.os.Handler;
29import android.text.TextUtils;
30import android.util.Log;
31import android.view.Menu;
32import android.view.MenuItem;
33import android.view.View;
34import android.widget.TextView;
35
36import com.android.email.Controller;
37import com.android.email.ControllerResultUiThreadWrapper;
38import com.android.email.Email;
39import com.android.email.MessageListContext;
40import com.android.email.MessagingExceptionStrings;
41import com.android.email.R;
42import com.android.emailcommon.Logging;
43import com.android.emailcommon.mail.MessagingException;
44import com.android.emailcommon.provider.Account;
45import com.android.emailcommon.provider.EmailContent.MailboxColumns;
46import com.android.emailcommon.provider.EmailContent.Message;
47import com.android.emailcommon.provider.Mailbox;
48import com.android.emailcommon.utility.EmailAsyncTask;
49import com.google.common.base.Preconditions;
50
51import java.util.ArrayList;
52
53/**
54 * The main Email activity, which is used on both the tablet and the phone.
55 *
56 * Because this activity is device agnostic, so most of the UI aren't owned by this, but by
57 * the UIController.
58 */
59public class EmailActivity extends Activity implements View.OnClickListener, FragmentInstallable {
60    public static final String EXTRA_ACCOUNT_ID = "ACCOUNT_ID";
61    public static final String EXTRA_MAILBOX_ID = "MAILBOX_ID";
62    public static final String EXTRA_MESSAGE_ID = "MESSAGE_ID";
63    public static final String EXTRA_QUERY_STRING = "QUERY_STRING";
64
65    /** Loader IDs starting with this is safe to use from UIControllers. */
66    static final int UI_CONTROLLER_LOADER_ID_BASE = 100;
67
68    /** Loader IDs starting with this is safe to use from ActionBarController. */
69    static final int ACTION_BAR_CONTROLLER_LOADER_ID_BASE = 200;
70
71    private static final int MAILBOX_SYNC_FREQUENCY_DIALOG = 1;
72    private static final int MAILBOX_SYNC_LOOKBACK_DIALOG = 2;
73
74    private Controller mController;
75    private Controller.Result mControllerResult;
76
77    private UIControllerBase mUIController;
78
79    private final EmailAsyncTask.Tracker mTaskTracker = new EmailAsyncTask.Tracker();
80
81    /** Banner to display errors */
82    private BannerController mErrorBanner;
83    /** Id of the account that had a messaging exception most recently. */
84    private long mLastErrorAccountId;
85
86    // STOPSHIP Temporary mailbox settings UI
87    private int mDialogSelection = -1;
88
89    /**
90     * Create an intent to launch and open account's inbox.
91     *
92     * @param accountId If -1, default account will be used.
93     */
94    public static Intent createOpenAccountIntent(Activity fromActivity, long accountId) {
95        Intent i = IntentUtilities.createRestartAppIntent(fromActivity, EmailActivity.class);
96        if (accountId != -1) {
97            i.putExtra(EXTRA_ACCOUNT_ID, accountId);
98        }
99        return i;
100    }
101
102    /**
103     * Create an intent to launch and open a mailbox.
104     *
105     * @param accountId must not be -1.
106     * @param mailboxId must not be -1.  Magic mailboxes IDs (such as
107     * {@link Mailbox#QUERY_ALL_INBOXES}) don't work.
108     */
109    public static Intent createOpenMailboxIntent(Activity fromActivity, long accountId,
110            long mailboxId) {
111        if (accountId == -1 || mailboxId == -1) {
112            throw new IllegalArgumentException();
113        }
114        Intent i = IntentUtilities.createRestartAppIntent(fromActivity, EmailActivity.class);
115        i.putExtra(EXTRA_ACCOUNT_ID, accountId);
116        i.putExtra(EXTRA_MAILBOX_ID, mailboxId);
117        return i;
118    }
119
120    /**
121     * Create an intent to launch and open a message.
122     *
123     * @param accountId must not be -1.
124     * @param mailboxId must not be -1.  Magic mailboxes IDs (such as
125     * {@link Mailbox#QUERY_ALL_INBOXES}) don't work.
126     * @param messageId must not be -1.
127     */
128    public static Intent createOpenMessageIntent(Activity fromActivity, long accountId,
129            long mailboxId, long messageId) {
130        if (accountId == -1 || mailboxId == -1 || messageId == -1) {
131            throw new IllegalArgumentException();
132        }
133        Intent i = IntentUtilities.createRestartAppIntent(fromActivity, EmailActivity.class);
134        i.putExtra(EXTRA_ACCOUNT_ID, accountId);
135        i.putExtra(EXTRA_MAILBOX_ID, mailboxId);
136        i.putExtra(EXTRA_MESSAGE_ID, messageId);
137        return i;
138    }
139
140    /**
141     * Create an intent to launch search activity.
142     *
143     * @param accountId ID of the account for the mailbox.  Must not be {@link Account#NO_ACCOUNT}.
144     * @param mailboxId ID of the mailbox to search, or {@link Mailbox#NO_MAILBOX} to perform
145     *     global search.
146     * @param query query string.
147     */
148    public static Intent createSearchIntent(Activity fromActivity, long accountId,
149            long mailboxId, String query) {
150        Preconditions.checkArgument(Account.isNormalAccount(accountId),
151                "Can only search in normal accounts");
152
153        // Note that a search doesn't use a restart intent, as we want another instance of
154        // the activity to sit on the stack for search.
155        Intent i = new Intent(fromActivity, EmailActivity.class);
156        i.putExtra(EXTRA_ACCOUNT_ID, accountId);
157        i.putExtra(EXTRA_MAILBOX_ID, mailboxId);
158        i.putExtra(EXTRA_QUERY_STRING, query);
159        i.setAction(Intent.ACTION_SEARCH);
160        return i;
161    }
162
163    /**
164     * Initialize {@link #mUIController}.
165     */
166    private void initUIController() {
167        mUIController = UiUtilities.useTwoPane(this)
168                ? new UIControllerTwoPane(this) : new UIControllerOnePane(this);
169    }
170
171    @Override
172    protected void onCreate(Bundle savedInstanceState) {
173        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) Log.d(Logging.LOG_TAG, this + " onCreate");
174
175        // UIController is used in onPrepareOptionsMenu(), which can be called from within
176        // super.onCreate(), so we need to initialize it here.
177        initUIController();
178
179        super.onCreate(savedInstanceState);
180        ActivityHelper.debugSetWindowFlags(this);
181        setContentView(mUIController.getLayoutId());
182
183        mUIController.onActivityViewReady();
184
185        mController = Controller.getInstance(this);
186        mControllerResult = new ControllerResultUiThreadWrapper<ControllerResult>(new Handler(),
187                new ControllerResult());
188        mController.addResultCallback(mControllerResult);
189
190        // Set up views
191        // TODO Probably better to extract mErrorMessageView related code into a separate class,
192        // so that it'll be easy to reuse for the phone activities.
193        TextView errorMessage = (TextView) findViewById(R.id.error_message);
194        errorMessage.setOnClickListener(this);
195        int errorBannerHeight = getResources().getDimensionPixelSize(R.dimen.error_message_height);
196        mErrorBanner = new BannerController(this, errorMessage, errorBannerHeight);
197
198        if (savedInstanceState != null) {
199            mUIController.onRestoreInstanceState(savedInstanceState);
200        } else {
201            initFromIntent();
202        }
203        mUIController.onActivityCreated();
204    }
205
206    private void initFromIntent() {
207        final Intent intent = getIntent();
208        final MessageListContext viewContext = MessageListContext.forIntent(this, intent);
209        final long messageId = intent.getLongExtra(EXTRA_MESSAGE_ID, Message.NO_MESSAGE);
210
211        mUIController.open(viewContext, messageId);
212    }
213
214    @Override
215    protected void onSaveInstanceState(Bundle outState) {
216        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
217            Log.d(Logging.LOG_TAG, this + " onSaveInstanceState");
218        }
219        super.onSaveInstanceState(outState);
220        mUIController.onSaveInstanceState(outState);
221    }
222
223    // FragmentInstallable
224    @Override
225    public void onInstallFragment(Fragment fragment) {
226        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
227            Log.d(Logging.LOG_TAG, this + " onInstallFragment fragment=" + fragment);
228        }
229        mUIController.onInstallFragment(fragment);
230    }
231
232    // FragmentInstallable
233    @Override
234    public void onUninstallFragment(Fragment fragment) {
235        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
236            Log.d(Logging.LOG_TAG, this + " onUninstallFragment fragment=" + fragment);
237        }
238        mUIController.onUninstallFragment(fragment);
239    }
240
241    @Override
242    protected void onStart() {
243        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) Log.d(Logging.LOG_TAG, this + " onStart");
244        super.onStart();
245        mUIController.onActivityStart();
246    }
247
248    @Override
249    protected void onResume() {
250        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) Log.d(Logging.LOG_TAG, this + " onResume");
251        super.onResume();
252        mUIController.onActivityResume();
253        /**
254         * In {@link MessageList#onResume()}, we go back to {@link Welcome} if an account
255         * has been added/removed. We don't need to do that here, because we fetch the most
256         * up-to-date account list. Additionally, we detect and do the right thing if all
257         * of the accounts have been removed.
258         */
259    }
260
261    @Override
262    protected void onPause() {
263        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) Log.d(Logging.LOG_TAG, this + " onPause");
264        super.onPause();
265        mUIController.onActivityPause();
266    }
267
268    @Override
269    protected void onStop() {
270        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) Log.d(Logging.LOG_TAG, this + " onStop");
271        super.onStop();
272        mUIController.onActivityStop();
273    }
274
275    @Override
276    protected void onDestroy() {
277        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) Log.d(Logging.LOG_TAG, this + " onDestroy");
278        mController.removeResultCallback(mControllerResult);
279        mTaskTracker.cancellAllInterrupt();
280        mUIController.onActivityDestroy();
281        super.onDestroy();
282    }
283
284    @Override
285    public void onBackPressed() {
286        if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
287            Log.d(Logging.LOG_TAG, this + " onBackPressed");
288        }
289        if (!mUIController.onBackPressed(true)) {
290            // Not handled by UIController -- perform the default. i.e. close the app.
291            super.onBackPressed();
292        }
293    }
294
295    @Override
296    public void onClick(View v) {
297        switch (v.getId()) {
298            case R.id.error_message:
299                dismissErrorMessage();
300                break;
301        }
302    }
303
304    /**
305     * Force dismiss the error banner.
306     */
307    private void dismissErrorMessage() {
308        mErrorBanner.dismiss();
309    }
310
311    @Override
312    public boolean onCreateOptionsMenu(Menu menu) {
313        return mUIController.onCreateOptionsMenu(getMenuInflater(), menu);
314    }
315
316    @Override
317    public boolean onPrepareOptionsMenu(Menu menu) {
318        return mUIController.onPrepareOptionsMenu(getMenuInflater(), menu);
319    }
320
321    /**
322     * Called when the search key is pressd.
323     *
324     * Use the below command to emulate the key press on devices without the search key.
325     * adb shell input keyevent 84
326     */
327    @Override
328    public boolean onSearchRequested() {
329        if (Email.DEBUG) {
330            Log.d(Logging.LOG_TAG, this + " onSearchRequested");
331        }
332        mUIController.onSearchRequested();
333        return true; // Event handled.
334    }
335
336    // STOPSHIP Set column from user options
337    private void setMailboxColumn(long mailboxId, String column, String value) {
338        if (mailboxId > 0) {
339            ContentValues cv = new ContentValues();
340            cv.put(column, value);
341            getContentResolver().update(
342                    ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId),
343                    cv, null, null);
344            mUIController.onRefresh();
345        }
346    }
347    // STOPSHIP Temporary mailbox settings UI.  If this ends up being useful, it should
348    // be moved to Utility (emailcommon)
349    private int findInStringArray(String[] array, String item) {
350        int i = 0;
351        for (String str: array) {
352            if (str.equals(item)) {
353                return i;
354            }
355            i++;
356        }
357        return -1;
358    }
359
360    // STOPSHIP Temporary mailbox settings UI
361    private final DialogInterface.OnClickListener mSelectionListener =
362        new DialogInterface.OnClickListener() {
363            public void onClick(DialogInterface dialog, int which) {
364                mDialogSelection = which;
365            }
366    };
367
368    // STOPSHIP Temporary mailbox settings UI
369    private final DialogInterface.OnClickListener mCancelListener =
370        new DialogInterface.OnClickListener() {
371            public void onClick(DialogInterface dialog, int which) {
372            }
373    };
374
375    // STOPSHIP Temporary mailbox settings UI
376    @Override
377    @Deprecated
378    protected Dialog onCreateDialog(int id, Bundle args) {
379        final long mailboxId = mUIController.getMailboxSettingsMailboxId();
380        if (mailboxId < 0) {
381            return null;
382        }
383        final Mailbox mailbox = Mailbox.restoreMailboxWithId(this, mailboxId);
384        if (mailbox == null) return null;
385        switch (id) {
386            case MAILBOX_SYNC_FREQUENCY_DIALOG:
387                String freq = Integer.toString(mailbox.mSyncInterval);
388                final String[] freqValues = getResources().getStringArray(
389                        R.array.account_settings_check_frequency_values_push);
390                int selection = findInStringArray(freqValues, freq);
391                // If not found, this is a push mailbox; trust me on this
392                if (selection == -1) selection = 0;
393                return new AlertDialog.Builder(this)
394                    .setIconAttribute(android.R.attr.dialogIcon)
395                    .setTitle(R.string.mailbox_options_check_frequency_label)
396                    .setSingleChoiceItems(R.array.account_settings_check_frequency_entries_push,
397                            selection,
398                            mSelectionListener)
399                    .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() {
400                        public void onClick(DialogInterface dialog, int which) {
401                            setMailboxColumn(mailboxId, MailboxColumns.SYNC_INTERVAL,
402                                    freqValues[mDialogSelection]);
403                        }})
404                    .setNegativeButton(R.string.cancel_action, mCancelListener)
405                   .create();
406
407            case MAILBOX_SYNC_LOOKBACK_DIALOG:
408                freq = Integer.toString(mailbox.mSyncLookback);
409                final String[] windowValues = getResources().getStringArray(
410                        R.array.account_settings_mail_window_values);
411                selection = findInStringArray(windowValues, freq);
412                return new AlertDialog.Builder(this)
413                    .setIconAttribute(android.R.attr.dialogIcon)
414                    .setTitle(R.string.mailbox_options_lookback_label)
415                    .setSingleChoiceItems(R.array.account_settings_mail_window_entries,
416                            selection,
417                            mSelectionListener)
418                    .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() {
419                        public void onClick(DialogInterface dialog, int which) {
420                            setMailboxColumn(mailboxId, MailboxColumns.SYNC_LOOKBACK,
421                                    windowValues[mDialogSelection]);
422                        }})
423                    .setNegativeButton(R.string.cancel_action, mCancelListener)
424                   .create();
425        }
426        return null;
427    }
428
429    @Override
430    @SuppressWarnings("deprecation")
431    public boolean onOptionsItemSelected(MenuItem item) {
432        if (mUIController.onOptionsItemSelected(item)) {
433            return true;
434        }
435        switch (item.getItemId()) {
436            // STOPSHIP Temporary mailbox settings UI
437            case R.id.sync_lookback:
438                showDialog(MAILBOX_SYNC_LOOKBACK_DIALOG);
439                return true;
440            // STOPSHIP Temporary mailbox settings UI
441            case R.id.sync_frequency:
442                showDialog(MAILBOX_SYNC_FREQUENCY_DIALOG);
443                return true;
444        }
445        return super.onOptionsItemSelected(item);
446    }
447
448
449    /**
450     * A {@link Controller.Result} to detect connection status.
451     */
452    private class ControllerResult extends Controller.Result {
453        @Override
454        public void sendMailCallback(
455                MessagingException result, long accountId, long messageId, int progress) {
456            handleError(result, accountId, progress);
457        }
458
459        @Override
460        public void serviceCheckMailCallback(
461                MessagingException result, long accountId, long mailboxId, int progress, long tag) {
462            handleError(result, accountId, progress);
463        }
464
465        @Override
466        public void updateMailboxCallback(MessagingException result, long accountId, long mailboxId,
467                int progress, int numNewMessages, ArrayList<Long> addedMessages) {
468            handleError(result, accountId, progress);
469        }
470
471        @Override
472        public void updateMailboxListCallback(
473                MessagingException result, long accountId, int progress) {
474            handleError(result, accountId, progress);
475        }
476
477        @Override
478        public void loadAttachmentCallback(MessagingException result, long accountId,
479                long messageId, long attachmentId, int progress) {
480            handleError(result, accountId, progress);
481        }
482
483        @Override
484        public void loadMessageForViewCallback(MessagingException result, long accountId,
485                long messageId, int progress) {
486            handleError(result, accountId, progress);
487        }
488
489        private void handleError(final MessagingException result, final long accountId,
490                int progress) {
491            if (accountId == -1) {
492                return;
493            }
494            if (result == null) {
495                if (progress > 0) {
496                    // Connection now working; clear the error message banner
497                    if (mLastErrorAccountId == accountId) {
498                        dismissErrorMessage();
499                    }
500                }
501            } else {
502                // Connection error; show the error message banner
503                new EmailAsyncTask<Void, Void, String>(mTaskTracker) {
504                    @Override
505                    protected String doInBackground(Void... params) {
506                        Account account =
507                            Account.restoreAccountWithId(EmailActivity.this, accountId);
508                        return (account == null) ? null : account.mDisplayName;
509                    }
510
511                    @Override
512                    protected void onPostExecute(String accountName) {
513                        String message =
514                            MessagingExceptionStrings.getErrorString(EmailActivity.this, result);
515                        if (!TextUtils.isEmpty(accountName)) {
516                            // TODO Use properly designed layout. Don't just concatenate strings;
517                            // which is generally poor for I18N.
518                            message = message + "   (" + accountName + ")";
519                        }
520                        if (mErrorBanner.show(message)) {
521                            mLastErrorAccountId = accountId;
522                        }
523                    }
524                }.executeParallel();
525            }
526        }
527    }
528}
529