EmailActivity.java revision 36f89da544a2a960ede047051c0d7b114d6d7717
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.Context; 26import android.content.DialogInterface; 27import android.content.Intent; 28import android.os.Bundle; 29import android.os.Handler; 30import android.text.TextUtils; 31import android.util.Log; 32import android.view.Menu; 33import android.view.MenuItem; 34import android.view.View; 35import android.widget.TextView; 36 37import com.android.email.Controller; 38import com.android.email.ControllerResultUiThreadWrapper; 39import com.android.email.Email; 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.service.SearchParams; 49import com.android.emailcommon.utility.EmailAsyncTask; 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 private static final String EXTRA_ACCOUNT_ID = "ACCOUNT_ID"; 61 private static final String EXTRA_MAILBOX_ID = "MAILBOX_ID"; 62 private static final String EXTRA_MESSAGE_ID = "MESSAGE_ID"; 63 private 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 Context mContext; 75 private Controller mController; 76 private Controller.Result mControllerResult; 77 78 private UIControllerBase mUIController; 79 80 private final EmailAsyncTask.Tracker mTaskTracker = new EmailAsyncTask.Tracker(); 81 82 /** Banner to display errors */ 83 private BannerController mErrorBanner; 84 /** Id of the account that had a messaging exception most recently. */ 85 private long mLastErrorAccountId; 86 87 // STOPSHIP Temporary mailbox settings UI 88 private int mDialogSelection = -1; 89 90 /** 91 * Create an intent to launch and open account's inbox. 92 * 93 * @param accountId If -1, default account will be used. 94 */ 95 public static Intent createOpenAccountIntent(Activity fromActivity, long accountId) { 96 Intent i = IntentUtilities.createRestartAppIntent(fromActivity, EmailActivity.class); 97 if (accountId != -1) { 98 i.putExtra(EXTRA_ACCOUNT_ID, accountId); 99 } 100 return i; 101 } 102 103 /** 104 * Create an intent to launch and open a mailbox. 105 * 106 * @param accountId must not be -1. 107 * @param mailboxId must not be -1. Magic mailboxes IDs (such as 108 * {@link Mailbox#QUERY_ALL_INBOXES}) don't work. 109 */ 110 public static Intent createOpenMailboxIntent(Activity fromActivity, long accountId, 111 long mailboxId) { 112 if (accountId == -1 || mailboxId == -1) { 113 throw new IllegalArgumentException(); 114 } 115 Intent i = IntentUtilities.createRestartAppIntent(fromActivity, EmailActivity.class); 116 i.putExtra(EXTRA_ACCOUNT_ID, accountId); 117 i.putExtra(EXTRA_MAILBOX_ID, mailboxId); 118 return i; 119 } 120 121 /** 122 * Create an intent to launch and open a message. 123 * 124 * @param accountId must not be -1. 125 * @param mailboxId must not be -1. Magic mailboxes IDs (such as 126 * {@link Mailbox#QUERY_ALL_INBOXES}) don't work. 127 * @param messageId must not be -1. 128 */ 129 public static Intent createOpenMessageIntent(Activity fromActivity, long accountId, 130 long mailboxId, long messageId) { 131 if (accountId == -1 || mailboxId == -1 || messageId == -1) { 132 throw new IllegalArgumentException(); 133 } 134 Intent i = IntentUtilities.createRestartAppIntent(fromActivity, EmailActivity.class); 135 i.putExtra(EXTRA_ACCOUNT_ID, accountId); 136 i.putExtra(EXTRA_MAILBOX_ID, mailboxId); 137 i.putExtra(EXTRA_MESSAGE_ID, messageId); 138 return i; 139 } 140 141 /** 142 * Create an intent to launch search activity. 143 * 144 * @param accountId ID of the account for the mailbox. Must not be {@link Account#NO_ACCOUNT}. 145 * @param mailboxId ID of the mailbox to search, or {@link Mailbox#NO_MAILBOX} to perform 146 * global search. 147 * @param query query string. 148 */ 149 public static Intent createSearchIntent(Activity fromActivity, long accountId, 150 long mailboxId, String query) { 151 if (!Account.isNormalAccount(accountId)) { 152 throw new IllegalArgumentException(); 153 } 154 Intent i = IntentUtilities.createRestartAppIntent(fromActivity, EmailActivity.class); 155 i.putExtra(EXTRA_ACCOUNT_ID, accountId); 156 i.putExtra(EXTRA_MAILBOX_ID, mailboxId); 157 i.putExtra(EXTRA_QUERY_STRING, query); 158 i.setAction(Intent.ACTION_SEARCH); 159 return i; 160 } 161 162 /** 163 * Initialize {@link #mUIController}. 164 */ 165 private void initUIController() { 166 mUIController = UiUtilities.useTwoPane(this) 167 ? new UIControllerTwoPane(this) : new UIControllerOnePane(this); 168 } 169 170 @Override 171 protected void onCreate(Bundle savedInstanceState) { 172 if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) Log.d(Logging.LOG_TAG, this + " onCreate"); 173 174 // UIController is used in onPrepareOptionsMenu(), which can be called from within 175 // super.onCreate(), so we need to initialize it here. 176 initUIController(); 177 178 super.onCreate(savedInstanceState); 179 ActivityHelper.debugSetWindowFlags(this); 180 setContentView(mUIController.getLayoutId()); 181 182 mUIController.onActivityViewReady(); 183 184 mContext = getApplicationContext(); 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 long accountId = intent.getLongExtra(EXTRA_ACCOUNT_ID, Account.NO_ACCOUNT); 209 final long mailboxId = intent.getLongExtra(EXTRA_MAILBOX_ID, Mailbox.NO_MAILBOX); 210 if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) { 211 Log.d(Logging.LOG_TAG, String.format("initFromIntent: %d %d", accountId, mailboxId)); 212 } 213 214 // STOPSHIP Temporary search UI 215 if (Intent.ACTION_SEARCH.equals(intent.getAction())) { 216 long searchMailboxId = Controller.getInstance(this).getSearchMailbox(accountId).mId; 217 final String queryTerm = intent.getStringExtra(EXTRA_QUERY_STRING); 218 EmailAsyncTask.runAsyncParallel(new Runnable() { 219 @Override 220 public void run() { 221 // TODO: do a global search in the case of EAS inbox 222 SearchParams searchSpec = new SearchParams(mailboxId, queryTerm); 223 try { 224 Controller.getInstance(EmailActivity.this).searchMessages( 225 accountId, searchSpec); 226 } catch (MessagingException e) { 227 // TODO: handle. 228 Log.e(Logging.LOG_TAG, "Got exception while searching " + e); 229 } 230 }}); 231 232 mUIController.open(accountId, searchMailboxId, Message.NO_MESSAGE); 233 } else { 234 final long messageId = intent.getLongExtra(EXTRA_MESSAGE_ID, Message.NO_MESSAGE); 235 if (accountId != Account.NO_ACCOUNT) { 236 mUIController.open(accountId, mailboxId, messageId); 237 } 238 } 239 } 240 241 @Override 242 protected void onSaveInstanceState(Bundle outState) { 243 if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) { 244 Log.d(Logging.LOG_TAG, this + " onSaveInstanceState"); 245 } 246 super.onSaveInstanceState(outState); 247 mUIController.onSaveInstanceState(outState); 248 } 249 250 // FragmentInstallable 251 @Override 252 public void onInstallFragment(Fragment fragment) { 253 if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) { 254 Log.d(Logging.LOG_TAG, this + " onInstallFragment fragment=" + fragment); 255 } 256 mUIController.onInstallFragment(fragment); 257 } 258 259 // FragmentInstallable 260 @Override 261 public void onUninstallFragment(Fragment fragment) { 262 if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) { 263 Log.d(Logging.LOG_TAG, this + " onUninstallFragment fragment=" + fragment); 264 } 265 mUIController.onUninstallFragment(fragment); 266 } 267 268 @Override 269 protected void onStart() { 270 if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) Log.d(Logging.LOG_TAG, this + " onStart"); 271 super.onStart(); 272 mUIController.onActivityStart(); 273 } 274 275 @Override 276 protected void onResume() { 277 if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) Log.d(Logging.LOG_TAG, this + " onResume"); 278 super.onResume(); 279 mUIController.onActivityResume(); 280 /** 281 * In {@link MessageList#onResume()}, we go back to {@link Welcome} if an account 282 * has been added/removed. We don't need to do that here, because we fetch the most 283 * up-to-date account list. Additionally, we detect and do the right thing if all 284 * of the accounts have been removed. 285 */ 286 } 287 288 @Override 289 protected void onPause() { 290 if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) Log.d(Logging.LOG_TAG, this + " onPause"); 291 super.onPause(); 292 mUIController.onActivityPause(); 293 } 294 295 @Override 296 protected void onStop() { 297 if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) Log.d(Logging.LOG_TAG, this + " onStop"); 298 super.onStop(); 299 mUIController.onActivityStop(); 300 } 301 302 @Override 303 protected void onDestroy() { 304 if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) Log.d(Logging.LOG_TAG, this + " onDestroy"); 305 mController.removeResultCallback(mControllerResult); 306 mTaskTracker.cancellAllInterrupt(); 307 mUIController.onActivityDestroy(); 308 super.onDestroy(); 309 } 310 311 @Override 312 public void onBackPressed() { 313 if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) { 314 Log.d(Logging.LOG_TAG, this + " onBackPressed"); 315 } 316 if (!mUIController.onBackPressed(true)) { 317 // Not handled by UIController -- perform the default. i.e. close the app. 318 super.onBackPressed(); 319 } 320 } 321 322 @Override 323 public void onClick(View v) { 324 switch (v.getId()) { 325 case R.id.error_message: 326 dismissErrorMessage(); 327 break; 328 } 329 } 330 331 /** 332 * Force dismiss the error banner. 333 */ 334 private void dismissErrorMessage() { 335 mErrorBanner.dismiss(); 336 } 337 338 @Override 339 public boolean onCreateOptionsMenu(Menu menu) { 340 return mUIController.onCreateOptionsMenu(getMenuInflater(), menu); 341 } 342 343 @Override 344 public boolean onPrepareOptionsMenu(Menu menu) { 345 // STOPSHIP Temporary sync options UI 346 boolean isEas = false; 347 boolean canSearch = false; 348 349 long accountId = mUIController.getActualAccountId(); 350 if (accountId > 0) { 351 // Move database operations out of the UI thread 352 if ("eas".equals(Account.getProtocol(mContext, accountId))) { 353 isEas = true; 354 Account account = Account.restoreAccountWithId(mContext, accountId); 355 if (account != null) { 356 // We should set a flag in the account indicating ability to handle search 357 String protocolVersion = account.mProtocolVersion; 358 if (Double.parseDouble(protocolVersion) >= 12.0) { 359 canSearch = true; 360 } 361 } 362 } else if ("imap".equals(Account.getProtocol(mContext, accountId))) { 363 canSearch = true; 364 } 365 } 366 367 // Should use an isSyncable call to prevent drafts/outbox from allowing this 368 menu.findItem(R.id.search).setVisible(canSearch); 369 menu.findItem(R.id.sync_lookback).setVisible(isEas); 370 menu.findItem(R.id.sync_frequency).setVisible(isEas); 371 372 return mUIController.onPrepareOptionsMenu(getMenuInflater(), menu); 373 } 374 375 /** 376 * Called when the search key is pressd. 377 * 378 * Use the below command to emulate the key press on devices without the search key. 379 * adb shell input keyevent 84 380 */ 381 @Override 382 public boolean onSearchRequested() { 383 if (Email.DEBUG) { 384 Log.d(Logging.LOG_TAG, this + " onSearchRequested"); 385 } 386 mUIController.onSearchRequested(); 387 return true; // Event handled. 388 } 389 390 // STOPSHIP Set column from user options 391 private void setMailboxColumn(long mailboxId, String column, String value) { 392 if (mailboxId > 0) { 393 ContentValues cv = new ContentValues(); 394 cv.put(column, value); 395 getContentResolver().update( 396 ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId), 397 cv, null, null); 398 mUIController.onRefresh(); 399 } 400 } 401 // STOPSHIP Temporary mailbox settings UI. If this ends up being useful, it should 402 // be moved to Utility (emailcommon) 403 private int findInStringArray(String[] array, String item) { 404 int i = 0; 405 for (String str: array) { 406 if (str.equals(item)) { 407 return i; 408 } 409 i++; 410 } 411 return -1; 412 } 413 414 // STOPSHIP Temporary mailbox settings UI 415 private final DialogInterface.OnClickListener mSelectionListener = 416 new DialogInterface.OnClickListener() { 417 public void onClick(DialogInterface dialog, int which) { 418 mDialogSelection = which; 419 } 420 }; 421 422 // STOPSHIP Temporary mailbox settings UI 423 private final DialogInterface.OnClickListener mCancelListener = 424 new DialogInterface.OnClickListener() { 425 public void onClick(DialogInterface dialog, int which) { 426 } 427 }; 428 429 // STOPSHIP Temporary mailbox settings UI 430 @Override 431 @Deprecated 432 protected Dialog onCreateDialog(int id, Bundle args) { 433 final long mailboxId = mUIController.getMailboxSettingsMailboxId(); 434 if (mailboxId < 0) { 435 return null; 436 } 437 final Mailbox mailbox = Mailbox.restoreMailboxWithId(this, mailboxId); 438 if (mailbox == null) return null; 439 switch (id) { 440 case MAILBOX_SYNC_FREQUENCY_DIALOG: 441 String freq = Integer.toString(mailbox.mSyncInterval); 442 final String[] freqValues = getResources().getStringArray( 443 R.array.account_settings_check_frequency_values_push); 444 int selection = findInStringArray(freqValues, freq); 445 // If not found, this is a push mailbox; trust me on this 446 if (selection == -1) selection = 0; 447 return new AlertDialog.Builder(this) 448 .setIconAttribute(android.R.attr.dialogIcon) 449 .setTitle(R.string.mailbox_options_check_frequency_label) 450 .setSingleChoiceItems(R.array.account_settings_check_frequency_entries_push, 451 selection, 452 mSelectionListener) 453 .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() { 454 public void onClick(DialogInterface dialog, int which) { 455 setMailboxColumn(mailboxId, MailboxColumns.SYNC_INTERVAL, 456 freqValues[mDialogSelection]); 457 }}) 458 .setNegativeButton(R.string.cancel_action, mCancelListener) 459 .create(); 460 461 case MAILBOX_SYNC_LOOKBACK_DIALOG: 462 freq = Integer.toString(mailbox.mSyncLookback); 463 final String[] windowValues = getResources().getStringArray( 464 R.array.account_settings_mail_window_values); 465 selection = findInStringArray(windowValues, freq); 466 return new AlertDialog.Builder(this) 467 .setIconAttribute(android.R.attr.dialogIcon) 468 .setTitle(R.string.mailbox_options_lookback_label) 469 .setSingleChoiceItems(R.array.account_settings_mail_window_entries, 470 selection, 471 mSelectionListener) 472 .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() { 473 public void onClick(DialogInterface dialog, int which) { 474 setMailboxColumn(mailboxId, MailboxColumns.SYNC_LOOKBACK, 475 windowValues[mDialogSelection]); 476 }}) 477 .setNegativeButton(R.string.cancel_action, mCancelListener) 478 .create(); 479 } 480 return null; 481 } 482 483 @Override 484 @SuppressWarnings("deprecation") 485 public boolean onOptionsItemSelected(MenuItem item) { 486 if (mUIController.onOptionsItemSelected(item)) { 487 return true; 488 } 489 switch (item.getItemId()) { 490 // STOPSHIP Temporary mailbox settings UI 491 case R.id.sync_lookback: 492 showDialog(MAILBOX_SYNC_LOOKBACK_DIALOG); 493 return true; 494 // STOPSHIP Temporary mailbox settings UI 495 case R.id.sync_frequency: 496 showDialog(MAILBOX_SYNC_FREQUENCY_DIALOG); 497 return true; 498 } 499 return super.onOptionsItemSelected(item); 500 } 501 502 503 /** 504 * A {@link Controller.Result} to detect connection status. 505 */ 506 private class ControllerResult extends Controller.Result { 507 @Override 508 public void sendMailCallback( 509 MessagingException result, long accountId, long messageId, int progress) { 510 handleError(result, accountId, progress); 511 } 512 513 @Override 514 public void serviceCheckMailCallback( 515 MessagingException result, long accountId, long mailboxId, int progress, long tag) { 516 handleError(result, accountId, progress); 517 } 518 519 @Override 520 public void updateMailboxCallback(MessagingException result, long accountId, long mailboxId, 521 int progress, int numNewMessages, ArrayList<Long> addedMessages) { 522 handleError(result, accountId, progress); 523 } 524 525 @Override 526 public void updateMailboxListCallback( 527 MessagingException result, long accountId, int progress) { 528 handleError(result, accountId, progress); 529 } 530 531 @Override 532 public void loadAttachmentCallback(MessagingException result, long accountId, 533 long messageId, long attachmentId, int progress) { 534 handleError(result, accountId, progress); 535 } 536 537 @Override 538 public void loadMessageForViewCallback(MessagingException result, long accountId, 539 long messageId, int progress) { 540 handleError(result, accountId, progress); 541 } 542 543 private void handleError(final MessagingException result, final long accountId, 544 int progress) { 545 if (accountId == -1) { 546 return; 547 } 548 if (result == null) { 549 if (progress > 0) { 550 // Connection now working; clear the error message banner 551 if (mLastErrorAccountId == accountId) { 552 dismissErrorMessage(); 553 } 554 } 555 } else { 556 // Connection error; show the error message banner 557 new EmailAsyncTask<Void, Void, String>(mTaskTracker) { 558 @Override 559 protected String doInBackground(Void... params) { 560 Account account = 561 Account.restoreAccountWithId(EmailActivity.this, accountId); 562 return (account == null) ? null : account.mDisplayName; 563 } 564 565 @Override 566 protected void onPostExecute(String accountName) { 567 String message = 568 MessagingExceptionStrings.getErrorString(EmailActivity.this, result); 569 if (!TextUtils.isEmpty(accountName)) { 570 // TODO Use properly designed layout. Don't just concatenate strings; 571 // which is generally poor for I18N. 572 message = message + " (" + accountName + ")"; 573 } 574 if (mErrorBanner.show(message)) { 575 mLastErrorAccountId = accountId; 576 } 577 } 578 }.executeParallel(); 579 } 580 } 581 } 582} 583