AccountSetupOptions.java revision 85e4c101b014857fe40f87c3837b82564cfc5b6c
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.activity.setup; 18 19import android.accounts.AccountAuthenticatorResponse; 20import android.accounts.AccountManager; 21import android.accounts.AccountManagerCallback; 22import android.accounts.AccountManagerFuture; 23import android.accounts.AuthenticatorException; 24import android.accounts.OperationCanceledException; 25import android.app.Activity; 26import android.app.AlertDialog; 27import android.content.Context; 28import android.content.DialogInterface; 29import android.content.Intent; 30import android.os.Bundle; 31import android.util.Log; 32import android.view.View; 33import android.view.View.OnClickListener; 34import android.widget.ArrayAdapter; 35import android.widget.CheckBox; 36import android.widget.Spinner; 37 38import com.android.email.Email; 39import com.android.email.ExchangeUtils; 40import com.android.email.R; 41import com.android.email.activity.ActivityHelper; 42import com.android.email.activity.UiUtilities; 43import com.android.email.service.MailService; 44import com.android.emailcommon.Logging; 45import com.android.emailcommon.provider.EmailContent; 46import com.android.emailcommon.provider.EmailContent.Account; 47import com.android.emailcommon.provider.HostAuth; 48import com.android.emailcommon.service.SyncWindow; 49import com.android.emailcommon.utility.Utility; 50 51import java.io.IOException; 52 53/** 54 * TODO: Cleanup the manipulation of Account.FLAGS_INCOMPLETE and make sure it's never left set. 55 */ 56public class AccountSetupOptions extends AccountSetupActivity implements OnClickListener { 57 58 private Spinner mCheckFrequencyView; 59 private Spinner mSyncWindowView; 60 private CheckBox mDefaultView; 61 private CheckBox mNotifyView; 62 private CheckBox mSyncContactsView; 63 private CheckBox mSyncCalendarView; 64 private CheckBox mSyncEmailView; 65 private CheckBox mBackgroundAttachmentsView; 66 private View mAccountSyncWindowRow; 67 private boolean mDonePressed = false; 68 69 public static final int REQUEST_CODE_ACCEPT_POLICIES = 1; 70 71 /** Default sync window for new EAS accounts */ 72 // STOPSHIP Change default for now to auto 73 private static final int SYNC_WINDOW_EAS_DEFAULT = SyncWindow.SYNC_WINDOW_AUTO; 74 // Was SYNC_WINDOW_3_DAYS; 75 76 public static void actionOptions(Activity fromActivity) { 77 fromActivity.startActivity(new Intent(fromActivity, AccountSetupOptions.class)); 78 } 79 80 @Override 81 public void onCreate(Bundle savedInstanceState) { 82 super.onCreate(savedInstanceState); 83 ActivityHelper.debugSetWindowFlags(this); 84 setContentView(R.layout.account_setup_options); 85 86 mCheckFrequencyView = (Spinner) UiUtilities.getView(this, R.id.account_check_frequency); 87 mSyncWindowView = (Spinner) UiUtilities.getView(this, R.id.account_sync_window); 88 mDefaultView = (CheckBox) UiUtilities.getView(this, R.id.account_default); 89 mNotifyView = (CheckBox) UiUtilities.getView(this, R.id.account_notify); 90 mSyncContactsView = (CheckBox) UiUtilities.getView(this, R.id.account_sync_contacts); 91 mSyncCalendarView = (CheckBox) UiUtilities.getView(this, R.id.account_sync_calendar); 92 mSyncEmailView = (CheckBox) UiUtilities.getView(this, R.id.account_sync_email); 93 mSyncEmailView.setChecked(true); 94 mBackgroundAttachmentsView = (CheckBox) UiUtilities.getView(this, 95 R.id.account_background_attachments); 96 mBackgroundAttachmentsView.setChecked(true); 97 UiUtilities.getView(this, R.id.previous).setOnClickListener(this); 98 UiUtilities.getView(this, R.id.next).setOnClickListener(this); 99 mAccountSyncWindowRow = UiUtilities.getView(this, R.id.account_sync_window_row); 100 101 // Generate spinner entries using XML arrays used by the preferences 102 int frequencyValuesId; 103 int frequencyEntriesId; 104 Account account = SetupData.getAccount(); 105 String protocol = account.mHostAuthRecv.mProtocol; 106 boolean eas = HostAuth.SCHEME_EAS.equals(protocol); 107 if (eas) { 108 frequencyValuesId = R.array.account_settings_check_frequency_values_push; 109 frequencyEntriesId = R.array.account_settings_check_frequency_entries_push; 110 } else { 111 frequencyValuesId = R.array.account_settings_check_frequency_values; 112 frequencyEntriesId = R.array.account_settings_check_frequency_entries; 113 } 114 CharSequence[] frequencyValues = getResources().getTextArray(frequencyValuesId); 115 CharSequence[] frequencyEntries = getResources().getTextArray(frequencyEntriesId); 116 117 // Now create the array used by the Spinner 118 SpinnerOption[] checkFrequencies = new SpinnerOption[frequencyEntries.length]; 119 for (int i = 0; i < frequencyEntries.length; i++) { 120 checkFrequencies[i] = new SpinnerOption( 121 Integer.valueOf(frequencyValues[i].toString()), frequencyEntries[i].toString()); 122 } 123 124 ArrayAdapter<SpinnerOption> checkFrequenciesAdapter = new ArrayAdapter<SpinnerOption>(this, 125 android.R.layout.simple_spinner_item, checkFrequencies); 126 checkFrequenciesAdapter 127 .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 128 mCheckFrequencyView.setAdapter(checkFrequenciesAdapter); 129 130 if (eas) { 131 enableEASSyncWindowSpinner(); 132 } 133 134 // Note: It is OK to use mAccount.mIsDefault here *only* because the account 135 // has not been written to the DB yet. Ordinarily, call Account.getDefaultAccountId(). 136 if (account.mIsDefault || SetupData.isDefault()) { 137 mDefaultView.setChecked(true); 138 } 139 mNotifyView.setChecked( 140 (account.getFlags() & EmailContent.Account.FLAGS_NOTIFY_NEW_MAIL) != 0); 141 SpinnerOption.setSpinnerOptionValue(mCheckFrequencyView, account.getSyncInterval()); 142 143 // Setup any additional items to support EAS & EAS flow mode 144 if (eas) { 145 // "also sync contacts" == "true" 146 mSyncContactsView.setVisibility(View.VISIBLE); 147 mSyncContactsView.setChecked(true); 148 mSyncCalendarView.setVisibility(View.VISIBLE); 149 mSyncCalendarView.setChecked(true); 150 // Show the associated dividers 151 UiUtilities.setVisibilitySafe(this, R.id.account_sync_contacts_divider, View.VISIBLE); 152 UiUtilities.setVisibilitySafe(this, R.id.account_sync_calendar_divider, View.VISIBLE); 153 } 154 155 // If we are in POP3, hide the "Background Attachments" mode 156 if (HostAuth.SCHEME_POP3.equals(protocol)) { 157 mBackgroundAttachmentsView.setVisibility(View.GONE); 158 UiUtilities.setVisibilitySafe(this, R.id.account_background_attachments_divider, 159 View.GONE); 160 } 161 162 // If we are just visiting here to fill in details, exit immediately 163 if (SetupData.isAutoSetup() || 164 SetupData.getFlowMode() == SetupData.FLOW_MODE_FORCE_CREATE) { 165 onDone(); 166 } 167 } 168 169 @Override 170 public void finish() { 171 // If the account manager initiated the creation, and success was not reported, 172 // then we assume that we're giving up (for any reason) - report failure. 173 AccountAuthenticatorResponse authenticatorResponse = 174 SetupData.getAccountAuthenticatorResponse(); 175 if (authenticatorResponse != null) { 176 authenticatorResponse.onError(AccountManager.ERROR_CODE_CANCELED, "canceled"); 177 SetupData.setAccountAuthenticatorResponse(null); 178 } 179 super.finish(); 180 } 181 182 /** 183 * Respond to clicks in the "Next" or "Previous" buttons 184 */ 185 @Override 186 public void onClick(View view) { 187 switch (view.getId()) { 188 case R.id.next: 189 // Don't allow this more than once (Exchange accounts call an async method 190 // before finish()'ing the Activity, which allows this code to potentially be 191 // executed multiple times 192 if (!mDonePressed) { 193 onDone(); 194 mDonePressed = true; 195 } 196 break; 197 case R.id.previous: 198 onBackPressed(); 199 break; 200 } 201 } 202 203 /** 204 * Ths is called when the user clicks the "done" button. 205 * It collects the data from the UI, updates the setup account record, and commits 206 * the account to the database (making it real for the first time.) 207 * Finally, we call setupAccountManagerAccount(), which will eventually complete via callback. 208 */ 209 private void onDone() { 210 final Account account = SetupData.getAccount(); 211 account.setDisplayName(account.getEmailAddress()); 212 int newFlags = account.getFlags() & 213 ~(Account.FLAGS_NOTIFY_NEW_MAIL | Account.FLAGS_BACKGROUND_ATTACHMENTS); 214 if (mNotifyView.isChecked()) { 215 newFlags |= Account.FLAGS_NOTIFY_NEW_MAIL; 216 } 217 if (mBackgroundAttachmentsView.isChecked()) { 218 newFlags |= Account.FLAGS_BACKGROUND_ATTACHMENTS; 219 } 220 account.setFlags(newFlags); 221 account.setSyncInterval((Integer)((SpinnerOption)mCheckFrequencyView 222 .getSelectedItem()).value); 223 if (mAccountSyncWindowRow.getVisibility() == View.VISIBLE) { 224 int window = (Integer)((SpinnerOption)mSyncWindowView.getSelectedItem()).value; 225 account.setSyncLookback(window); 226 } 227 account.setDefaultAccount(mDefaultView.isChecked()); 228 229 if (account.isSaved()) { 230 throw new IllegalStateException("in AccountSetupOptions with already-saved account"); 231 } 232 if (account.mHostAuthRecv == null) { 233 throw new IllegalStateException("in AccountSetupOptions with null mHostAuthRecv"); 234 } 235 236 // Finish setting up the account, and commit it to the database 237 // Set the incomplete flag here to avoid reconciliation issues in ExchangeService 238 account.mFlags |= Account.FLAGS_INCOMPLETE; 239 boolean calendar = false; 240 boolean contacts = false; 241 boolean email = mSyncEmailView.isChecked(); 242 if (account.mHostAuthRecv.mProtocol.equals("eas")) { 243 if (SetupData.getPolicy() != null) { 244 account.mFlags |= Account.FLAGS_SECURITY_HOLD; 245 account.mPolicy = SetupData.getPolicy(); 246 } 247 // Get flags for contacts/calendar sync 248 contacts = mSyncContactsView.isChecked(); 249 calendar = mSyncCalendarView.isChecked(); 250 } 251 252 // Finally, write the completed account (for the first time) and then 253 // install it into the Account manager as well. These are done off-thread. 254 // The account manager will report back via the callback, which will take us to 255 // the next operations. 256 final boolean email2 = email; 257 final boolean calendar2 = calendar; 258 final boolean contacts2 = contacts; 259 Utility.runAsync(new Runnable() { 260 @Override 261 public void run() { 262 Context context = AccountSetupOptions.this; 263 AccountSettingsUtils.commitSettings(context, account); 264 MailService.setupAccountManagerAccount(context, account, 265 email2, calendar2, contacts2, mAccountManagerCallback); 266 } 267 }); 268 } 269 270 /** 271 * This is called at the completion of MailService.setupAccountManagerAccount() 272 */ 273 AccountManagerCallback<Bundle> mAccountManagerCallback = new AccountManagerCallback<Bundle>() { 274 public void run(AccountManagerFuture<Bundle> future) { 275 try { 276 Bundle bundle = future.getResult(); 277 bundle.keySet(); 278 AccountSetupOptions.this.runOnUiThread(new Runnable() { 279 public void run() { 280 optionsComplete(); 281 } 282 }); 283 return; 284 } catch (OperationCanceledException e) { 285 Log.d(Logging.LOG_TAG, "addAccount was canceled"); 286 } catch (IOException e) { 287 Log.d(Logging.LOG_TAG, "addAccount failed: " + e); 288 } catch (AuthenticatorException e) { 289 Log.d(Logging.LOG_TAG, "addAccount failed: " + e); 290 } 291 showErrorDialog(R.string.account_setup_failed_dlg_auth_message, 292 R.string.system_account_create_failed); 293 } 294 }; 295 296 /** 297 * This is called if MailService.setupAccountManagerAccount() fails for some reason 298 */ 299 private void showErrorDialog(final int msgResId, final Object... args) { 300 runOnUiThread(new Runnable() { 301 public void run() { 302 new AlertDialog.Builder(AccountSetupOptions.this) 303 .setIconAttribute(android.R.attr.alertDialogIcon) 304 .setTitle(getString(R.string.account_setup_failed_dlg_title)) 305 .setMessage(getString(msgResId, args)) 306 .setCancelable(true) 307 .setPositiveButton( 308 getString(R.string.account_setup_failed_dlg_edit_details_action), 309 new DialogInterface.OnClickListener() { 310 public void onClick(DialogInterface dialog, int which) { 311 finish(); 312 } 313 }) 314 .show(); 315 } 316 }); 317 } 318 319 /** 320 * This is called after the account manager creates the new account. 321 */ 322 private void optionsComplete() { 323 // If the account manager initiated the creation, report success at this point 324 AccountAuthenticatorResponse authenticatorResponse = 325 SetupData.getAccountAuthenticatorResponse(); 326 if (authenticatorResponse != null) { 327 authenticatorResponse.onResult(null); 328 SetupData.setAccountAuthenticatorResponse(null); 329 } 330 331 // If we've got policies for this account, ask the user to accept. 332 Account account = SetupData.getAccount(); 333 if ((account.mFlags & Account.FLAGS_SECURITY_HOLD) != 0) { 334 Intent intent = AccountSecurity.actionUpdateSecurityIntent(this, account.mId, false); 335 startActivityForResult(intent, AccountSetupOptions.REQUEST_CODE_ACCEPT_POLICIES); 336 return; 337 } 338 saveAccountAndFinish(); 339 } 340 341 /** 342 * This is called after the AccountSecurity activity completes. 343 */ 344 @Override 345 public void onActivityResult(int requestCode, int resultCode, Intent data) { 346 saveAccountAndFinish(); 347 } 348 349 /** 350 * These are the final cleanup steps when creating an account: 351 * Clear incomplete & security hold flags 352 * Update account in DB 353 * Enable email services 354 * Enable exchange services 355 * Move to final setup screen 356 */ 357 private void saveAccountAndFinish() { 358 Utility.runAsync(new Runnable() { 359 @Override 360 public void run() { 361 AccountSetupOptions context = AccountSetupOptions.this; 362 // Clear the incomplete/security hold flag now 363 Account account = SetupData.getAccount(); 364 account.mFlags &= ~(Account.FLAGS_INCOMPLETE | Account.FLAGS_SECURITY_HOLD); 365 AccountSettingsUtils.commitSettings(context, account); 366 // Start up services based on new account(s) 367 Email.setServicesEnabledSync(context); 368 ExchangeUtils.startExchangeService(context); 369 // Move to final setup screen 370 AccountSetupNames.actionSetNames(context); 371 finish(); 372 } 373 }); 374 } 375 376 /** 377 * Enable an additional spinner using the arrays normally handled by preferences 378 */ 379 private void enableEASSyncWindowSpinner() { 380 // Show everything 381 mAccountSyncWindowRow.setVisibility(View.VISIBLE); 382 383 // Generate spinner entries using XML arrays used by the preferences 384 CharSequence[] windowValues = getResources().getTextArray( 385 R.array.account_settings_mail_window_values); 386 CharSequence[] windowEntries = getResources().getTextArray( 387 R.array.account_settings_mail_window_entries); 388 389 // Now create the array used by the Spinner 390 SpinnerOption[] windowOptions = new SpinnerOption[windowEntries.length]; 391 int defaultIndex = -1; 392 for (int i = 0; i < windowEntries.length; i++) { 393 final int value = Integer.valueOf(windowValues[i].toString()); 394 windowOptions[i] = new SpinnerOption(value, windowEntries[i].toString()); 395 if (value == SYNC_WINDOW_EAS_DEFAULT) { 396 defaultIndex = i; 397 } 398 } 399 400 ArrayAdapter<SpinnerOption> windowOptionsAdapter = new ArrayAdapter<SpinnerOption>(this, 401 android.R.layout.simple_spinner_item, windowOptions); 402 windowOptionsAdapter 403 .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 404 mSyncWindowView.setAdapter(windowOptionsAdapter); 405 406 SpinnerOption.setSpinnerOptionValue(mSyncWindowView, 407 SetupData.getAccount().getSyncLookback()); 408 if (defaultIndex >= 0) { 409 mSyncWindowView.setSelection(defaultIndex); 410 } 411 } 412} 413