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