AccountSettingsFragment.java revision bc2eaadde987044027b57d241e635de014bdb8ba
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.setup; 18 19import android.app.Activity; 20import android.app.AlertDialog; 21import android.app.Dialog; 22import android.app.DialogFragment; 23import android.app.Fragment; 24import android.app.FragmentTransaction; 25import android.content.ContentResolver; 26import android.content.ContentValues; 27import android.content.Context; 28import android.content.DialogInterface; 29import android.content.SharedPreferences; 30import android.os.AsyncTask; 31import android.os.Bundle; 32import android.os.Vibrator; 33import android.preference.CheckBoxPreference; 34import android.preference.EditTextPreference; 35import android.preference.ListPreference; 36import android.preference.Preference; 37import android.preference.PreferenceCategory; 38import android.preference.PreferenceFragment; 39import android.preference.RingtonePreference; 40import android.provider.ContactsContract; 41import android.text.TextUtils; 42import android.util.Log; 43 44import com.android.email.Email; 45import com.android.email.R; 46import com.android.email.mail.Sender; 47import com.android.emailcommon.AccountManagerTypes; 48import com.android.emailcommon.CalendarProviderStub; 49import com.android.emailcommon.Logging; 50import com.android.emailcommon.mail.MessagingException; 51import com.android.emailcommon.provider.Account; 52import com.android.emailcommon.provider.EmailContent; 53import com.android.emailcommon.provider.HostAuth; 54import com.android.emailcommon.utility.Utility; 55 56/** 57 * Fragment containing the main logic for account settings. This also calls out to other 58 * fragments for server settings. 59 * 60 * TODO: Remove or make async the mAccountDirty reload logic. Probably no longer needed. 61 * TODO: Can we defer calling addPreferencesFromResource() until after we load the account? This 62 * could reduce flicker. 63 */ 64public class AccountSettingsFragment extends PreferenceFragment { 65 66 // Keys used for arguments bundle 67 private static final String BUNDLE_KEY_ACCOUNT_ID = "AccountSettingsFragment.AccountId"; 68 private static final String BUNDLE_KEY_ACCOUNT_EMAIL = "AccountSettingsFragment.Email"; 69 70 private static final String PREFERENCE_CATEGORY_TOP = "account_settings"; 71 public static final String PREFERENCE_DESCRIPTION = "account_description"; 72 private static final String PREFERENCE_NAME = "account_name"; 73 private static final String PREFERENCE_SIGNATURE = "account_signature"; 74 private static final String PREFERENCE_QUICK_RESPONSES = "account_quick_responses"; 75 private static final String PREFERENCE_FREQUENCY = "account_check_frequency"; 76 private static final String PREFERENCE_BACKGROUND_ATTACHMENTS = 77 "account_background_attachments"; 78 private static final String PREFERENCE_DEFAULT = "account_default"; 79 private static final String PREFERENCE_CATEGORY_NOTIFICATIONS = "account_notifications"; 80 private static final String PREFERENCE_NOTIFY = "account_notify"; 81 private static final String PREFERENCE_VIBRATE_WHEN = "account_settings_vibrate_when"; 82 private static final String PREFERENCE_RINGTONE = "account_ringtone"; 83 private static final String PREFERENCE_CATEGORY_SERVER = "account_servers"; 84 private static final String PREFERENCE_INCOMING = "incoming"; 85 private static final String PREFERENCE_OUTGOING = "outgoing"; 86 private static final String PREFERENCE_SYNC_CONTACTS = "account_sync_contacts"; 87 private static final String PREFERENCE_SYNC_CALENDAR = "account_sync_calendar"; 88 private static final String PREFERENCE_SYNC_EMAIL = "account_sync_email"; 89 private static final String PREFERENCE_DELETE_ACCOUNT = "delete_account"; 90 91 // These strings must match account_settings_vibrate_when_* strings in strings.xml 92 private static final String PREFERENCE_VALUE_VIBRATE_WHEN_ALWAYS = "always"; 93 private static final String PREFERENCE_VALUE_VIBRATE_WHEN_SILENT = "silent"; 94 private static final String PREFERENCE_VALUE_VIBRATE_WHEN_NEVER = "never"; 95 96 private EditTextPreference mAccountDescription; 97 private EditTextPreference mAccountName; 98 private EditTextPreference mAccountSignature; 99 private ListPreference mCheckFrequency; 100 private ListPreference mSyncWindow; 101 private CheckBoxPreference mAccountBackgroundAttachments; 102 private CheckBoxPreference mAccountDefault; 103 private CheckBoxPreference mAccountNotify; 104 private ListPreference mAccountVibrateWhen; 105 private RingtonePreference mAccountRingtone; 106 private CheckBoxPreference mSyncContacts; 107 private CheckBoxPreference mSyncCalendar; 108 private CheckBoxPreference mSyncEmail; 109 110 private Context mContext; 111 private Account mAccount; 112 private boolean mAccountDirty; 113 private long mDefaultAccountId; 114 private Callback mCallback = EmptyCallback.INSTANCE; 115 private boolean mStarted; 116 private boolean mLoaded; 117 private boolean mSaveOnExit; 118 119 /** The e-mail of the account being edited. */ 120 private String mAccountEmail; 121 122 // Async Tasks 123 private AsyncTask<?,?,?> mLoadAccountTask; 124 125 /** 126 * Callback interface that owning activities must provide 127 */ 128 public interface Callback { 129 public void onSettingsChanged(Account account, String preference, Object value); 130 public void onEditQuickResponses(Account account); 131 public void onIncomingSettings(Account account); 132 public void onOutgoingSettings(Account account); 133 public void abandonEdit(); 134 public void deleteAccount(Account account); 135 } 136 137 private static class EmptyCallback implements Callback { 138 public static final Callback INSTANCE = new EmptyCallback(); 139 @Override public void onSettingsChanged(Account account, String preference, Object value) {} 140 @Override public void onEditQuickResponses(Account account) {} 141 @Override public void onIncomingSettings(Account account) {} 142 @Override public void onOutgoingSettings(Account account) {} 143 @Override public void abandonEdit() {} 144 @Override public void deleteAccount(Account account) {} 145 } 146 147 /** 148 * If launching with an arguments bundle, use this method to build the arguments. 149 */ 150 public static Bundle buildArguments(long accountId, String email) { 151 Bundle b = new Bundle(); 152 b.putLong(BUNDLE_KEY_ACCOUNT_ID, accountId); 153 b.putString(BUNDLE_KEY_ACCOUNT_EMAIL, email); 154 return b; 155 } 156 157 public static String getTitleFromArgs(Bundle args) { 158 return (args == null) ? null : args.getString(BUNDLE_KEY_ACCOUNT_EMAIL); 159 } 160 161 @Override 162 public void onAttach(Activity activity) { 163 super.onAttach(activity); 164 mContext = activity; 165 } 166 167 /** 168 * Called to do initial creation of a fragment. This is called after 169 * {@link #onAttach(Activity)} and before {@link #onActivityCreated(Bundle)}. 170 */ 171 @Override 172 public void onCreate(Bundle savedInstanceState) { 173 if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) { 174 Log.d(Logging.LOG_TAG, "AccountSettingsFragment onCreate"); 175 } 176 super.onCreate(savedInstanceState); 177 178 // Load the preferences from an XML resource 179 addPreferencesFromResource(R.xml.account_settings_preferences); 180 181 // Start loading the account data, if provided in the arguments 182 // If not, activity must call startLoadingAccount() directly 183 Bundle b = getArguments(); 184 if (b != null) { 185 long accountId = b.getLong(BUNDLE_KEY_ACCOUNT_ID, -1); 186 mAccountEmail = b.getString(BUNDLE_KEY_ACCOUNT_EMAIL); 187 if (accountId >= 0 && !mLoaded) { 188 startLoadingAccount(accountId); 189 } 190 } 191 192 mAccountDirty = false; 193 } 194 195 @Override 196 public void onActivityCreated(Bundle savedInstanceState) { 197 if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) { 198 Log.d(Logging.LOG_TAG, "AccountSettingsFragment onActivityCreated"); 199 } 200 super.onActivityCreated(savedInstanceState); 201 } 202 203 /** 204 * Called when the Fragment is visible to the user. 205 */ 206 @Override 207 public void onStart() { 208 if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) { 209 Log.d(Logging.LOG_TAG, "AccountSettingsFragment onStart"); 210 } 211 super.onStart(); 212 mStarted = true; 213 214 // If the loaded account is ready now, load the UI 215 if (mAccount != null && !mLoaded) { 216 loadSettings(); 217 } 218 } 219 220 /** 221 * Called when the fragment is visible to the user and actively running. 222 * TODO: Don't read account data on UI thread. This should be fixed by removing the need 223 * to do this, not by spinning up yet another thread. 224 */ 225 @Override 226 public void onResume() { 227 if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) { 228 Log.d(Logging.LOG_TAG, "AccountSettingsFragment onResume"); 229 } 230 super.onResume(); 231 232 if (mAccountDirty) { 233 // if we are coming back from editing incoming or outgoing settings, 234 // we need to refresh them here so we don't accidentally overwrite the 235 // old values we're still holding here 236 mAccount.mHostAuthRecv = 237 HostAuth.restoreHostAuthWithId(mContext, mAccount.mHostAuthKeyRecv); 238 mAccount.mHostAuthSend = 239 HostAuth.restoreHostAuthWithId(mContext, mAccount.mHostAuthKeySend); 240 // Because "delete policy" UI is on edit incoming settings, we have 241 // to refresh that as well. 242 Account refreshedAccount = Account.restoreAccountWithId(mContext, mAccount.mId); 243 if (refreshedAccount == null || mAccount.mHostAuthRecv == null 244 || mAccount.mHostAuthSend == null) { 245 mSaveOnExit = false; 246 mCallback.abandonEdit(); 247 return; 248 } 249 mAccount.setDeletePolicy(refreshedAccount.getDeletePolicy()); 250 mAccountDirty = false; 251 } 252 } 253 254 @Override 255 public void onPause() { 256 if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) { 257 Log.d(Logging.LOG_TAG, "AccountSettingsFragment onPause"); 258 } 259 super.onPause(); 260 if (mSaveOnExit) { 261 saveSettings(); 262 } 263 } 264 265 /** 266 * Called when the Fragment is no longer started. 267 */ 268 @Override 269 public void onStop() { 270 if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) { 271 Log.d(Logging.LOG_TAG, "AccountSettingsFragment onStop"); 272 } 273 super.onStop(); 274 mStarted = false; 275 } 276 277 /** 278 * Called when the fragment is no longer in use. 279 */ 280 @Override 281 public void onDestroy() { 282 if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) { 283 Log.d(Logging.LOG_TAG, "AccountSettingsFragment onDestroy"); 284 } 285 super.onDestroy(); 286 287 Utility.cancelTaskInterrupt(mLoadAccountTask); 288 mLoadAccountTask = null; 289 } 290 291 @Override 292 public void onSaveInstanceState(Bundle outState) { 293 if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) { 294 Log.d(Logging.LOG_TAG, "AccountSettingsFragment onSaveInstanceState"); 295 } 296 super.onSaveInstanceState(outState); 297 } 298 299 /** 300 * Activity provides callbacks here 301 */ 302 public void setCallback(Callback callback) { 303 mCallback = (callback == null) ? EmptyCallback.INSTANCE : callback; 304 } 305 306 /** 307 * Start loading a single account in preparation for editing it 308 */ 309 public void startLoadingAccount(long accountId) { 310 Utility.cancelTaskInterrupt(mLoadAccountTask); 311 mLoadAccountTask = new LoadAccountTask().executeOnExecutor( 312 AsyncTask.THREAD_POOL_EXECUTOR, accountId); 313 } 314 315 /** 316 * Async task to load account in order to view/edit it 317 */ 318 private class LoadAccountTask extends AsyncTask<Long, Void, Object[]> { 319 @Override 320 protected Object[] doInBackground(Long... params) { 321 long accountId = params[0]; 322 Account account = Account.restoreAccountWithId(mContext, accountId); 323 if (account != null) { 324 account.mHostAuthRecv = 325 HostAuth.restoreHostAuthWithId(mContext, account.mHostAuthKeyRecv); 326 account.mHostAuthSend = 327 HostAuth.restoreHostAuthWithId(mContext, account.mHostAuthKeySend); 328 if (account.mHostAuthRecv == null || account.mHostAuthSend == null) { 329 account = null; 330 } 331 } 332 long defaultAccountId = Account.getDefaultAccountId(mContext); 333 return new Object[] { account, Long.valueOf(defaultAccountId) }; 334 } 335 336 @Override 337 protected void onPostExecute(Object[] results) { 338 if (results != null && !isCancelled()) { 339 Account account = (Account) results[0]; 340 if (account == null) { 341 mSaveOnExit = false; 342 mCallback.abandonEdit(); 343 } else { 344 mAccount = account; 345 mDefaultAccountId = (Long) results[1]; 346 if (mStarted && !mLoaded) { 347 loadSettings(); 348 } 349 } 350 } 351 } 352 } 353 354 /** 355 * Load account data into preference UI 356 */ 357 private void loadSettings() { 358 // We can only do this once, so prevent repeat 359 mLoaded = true; 360 // Once loaded the data is ready to be saved, as well 361 mSaveOnExit = false; 362 363 PreferenceCategory topCategory = 364 (PreferenceCategory) findPreference(PREFERENCE_CATEGORY_TOP); 365 topCategory.setTitle(mContext.getString(R.string.account_settings_title_fmt)); 366 367 mAccountDescription = (EditTextPreference) findPreference(PREFERENCE_DESCRIPTION); 368 mAccountDescription.setSummary(mAccount.getDisplayName()); 369 mAccountDescription.setText(mAccount.getDisplayName()); 370 mAccountDescription.setOnPreferenceChangeListener( 371 new Preference.OnPreferenceChangeListener() { 372 public boolean onPreferenceChange(Preference preference, Object newValue) { 373 String summary = newValue.toString().trim(); 374 if (TextUtils.isEmpty(summary)) { 375 summary = mAccount.mEmailAddress; 376 } 377 mAccountDescription.setSummary(summary); 378 mAccountDescription.setText(summary); 379 onPreferenceChanged(PREFERENCE_DESCRIPTION, summary); 380 return false; 381 } 382 } 383 ); 384 385 mAccountName = (EditTextPreference) findPreference(PREFERENCE_NAME); 386 String senderName = mAccount.getSenderName(); 387 // In rare cases, sendername will be null; Change this to empty string to avoid NPE's 388 if (senderName == null) senderName = ""; 389 mAccountName.setSummary(senderName); 390 mAccountName.setText(senderName); 391 mAccountName.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { 392 public boolean onPreferenceChange(Preference preference, Object newValue) { 393 final String summary = newValue.toString().trim(); 394 if (!TextUtils.isEmpty(summary)) { 395 mAccountName.setSummary(summary); 396 mAccountName.setText(summary); 397 onPreferenceChanged(PREFERENCE_NAME, summary); 398 } 399 return false; 400 } 401 }); 402 403 mAccountSignature = (EditTextPreference) findPreference(PREFERENCE_SIGNATURE); 404 String signature = mAccount.getSignature(); 405 mAccountSignature.setText(mAccount.getSignature()); 406 mAccountSignature.setOnPreferenceChangeListener( 407 new Preference.OnPreferenceChangeListener() { 408 public boolean onPreferenceChange(Preference preference, Object newValue) { 409 // Clean up signature if it's only whitespace (which is easy to do on a 410 // soft keyboard) but leave whitespace in place otherwise, to give the user 411 // maximum flexibility, e.g. the ability to indent 412 String signature = newValue.toString(); 413 if (signature.trim().isEmpty()) { 414 signature = ""; 415 } 416 mAccountSignature.setText(signature); 417 onPreferenceChanged(PREFERENCE_SIGNATURE, signature); 418 return false; 419 } 420 }); 421 422 mCheckFrequency = (ListPreference) findPreference(PREFERENCE_FREQUENCY); 423 424 // TODO Move protocol into Account to avoid retrieving the HostAuth (implicitly) 425 String protocol = Account.getProtocol(mContext, mAccount.mId); 426 if (HostAuth.SCHEME_EAS.equals(protocol)) { 427 mCheckFrequency.setEntries(R.array.account_settings_check_frequency_entries_push); 428 mCheckFrequency.setEntryValues(R.array.account_settings_check_frequency_values_push); 429 } 430 431 mCheckFrequency.setValue(String.valueOf(mAccount.getSyncInterval())); 432 mCheckFrequency.setSummary(mCheckFrequency.getEntry()); 433 mCheckFrequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { 434 public boolean onPreferenceChange(Preference preference, Object newValue) { 435 final String summary = newValue.toString(); 436 int index = mCheckFrequency.findIndexOfValue(summary); 437 mCheckFrequency.setSummary(mCheckFrequency.getEntries()[index]); 438 mCheckFrequency.setValue(summary); 439 onPreferenceChanged(PREFERENCE_FREQUENCY, newValue); 440 return false; 441 } 442 }); 443 444 findPreference(PREFERENCE_QUICK_RESPONSES).setOnPreferenceClickListener( 445 new Preference.OnPreferenceClickListener() { 446 @Override 447 public boolean onPreferenceClick(Preference preference) { 448 mAccountDirty = true; 449 mCallback.onEditQuickResponses(mAccount); 450 return true; 451 } 452 }); 453 454 // Add check window preference 455 mSyncWindow = null; 456 if (HostAuth.SCHEME_EAS.equals(protocol)) { 457 mSyncWindow = new ListPreference(mContext); 458 mSyncWindow.setTitle(R.string.account_setup_options_mail_window_label); 459 mSyncWindow.setEntries(R.array.account_settings_mail_window_entries); 460 mSyncWindow.setEntryValues(R.array.account_settings_mail_window_values); 461 mSyncWindow.setValue(String.valueOf(mAccount.getSyncLookback())); 462 mSyncWindow.setSummary(mSyncWindow.getEntry()); 463 mSyncWindow.setOrder(5); 464 mSyncWindow.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { 465 public boolean onPreferenceChange(Preference preference, Object newValue) { 466 final String summary = newValue.toString(); 467 int index = mSyncWindow.findIndexOfValue(summary); 468 mSyncWindow.setSummary(mSyncWindow.getEntries()[index]); 469 mSyncWindow.setValue(summary); 470 onPreferenceChanged(preference.getKey(), newValue); 471 return false; 472 } 473 }); 474 topCategory.addPreference(mSyncWindow); 475 } 476 477 // Show "background attachments" for IMAP & EAS - hide it for POP3. 478 mAccountBackgroundAttachments = (CheckBoxPreference) 479 findPreference(PREFERENCE_BACKGROUND_ATTACHMENTS); 480 if (HostAuth.SCHEME_POP3.equals(mAccount.mHostAuthRecv.mProtocol)) { 481 topCategory.removePreference(mAccountBackgroundAttachments); 482 } else { 483 mAccountBackgroundAttachments.setChecked( 484 0 != (mAccount.getFlags() & Account.FLAGS_BACKGROUND_ATTACHMENTS)); 485 mAccountBackgroundAttachments.setOnPreferenceChangeListener(mPreferenceChangeListener); 486 } 487 488 mAccountDefault = (CheckBoxPreference) findPreference(PREFERENCE_DEFAULT); 489 mAccountDefault.setChecked(mAccount.mId == mDefaultAccountId); 490 mAccountDefault.setOnPreferenceChangeListener(mPreferenceChangeListener); 491 492 mAccountNotify = (CheckBoxPreference) findPreference(PREFERENCE_NOTIFY); 493 mAccountNotify.setChecked(0 != (mAccount.getFlags() & Account.FLAGS_NOTIFY_NEW_MAIL)); 494 mAccountNotify.setOnPreferenceChangeListener(mPreferenceChangeListener); 495 496 mAccountRingtone = (RingtonePreference) findPreference(PREFERENCE_RINGTONE); 497 mAccountRingtone.setOnPreferenceChangeListener(mPreferenceChangeListener); 498 499 // The following two lines act as a workaround for the RingtonePreference 500 // which does not let us set/get the value programmatically 501 SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences(); 502 prefs.edit().putString(PREFERENCE_RINGTONE, mAccount.getRingtone()).apply(); 503 504 // Set the vibrator value, or hide it on devices w/o a vibrator 505 mAccountVibrateWhen = (ListPreference) findPreference(PREFERENCE_VIBRATE_WHEN); 506 Vibrator vibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE); 507 if (vibrator.hasVibrator()) { 508 boolean flagsVibrate = 0 != (mAccount.getFlags() & Account.FLAGS_VIBRATE_ALWAYS); 509 boolean flagsVibrateSilent = 510 0 != (mAccount.getFlags() & Account.FLAGS_VIBRATE_WHEN_SILENT); 511 mAccountVibrateWhen.setValue( 512 flagsVibrate ? PREFERENCE_VALUE_VIBRATE_WHEN_ALWAYS : 513 flagsVibrateSilent ? PREFERENCE_VALUE_VIBRATE_WHEN_SILENT : 514 PREFERENCE_VALUE_VIBRATE_WHEN_NEVER); 515 mAccountVibrateWhen.setOnPreferenceChangeListener(mPreferenceChangeListener); 516 } else { 517 PreferenceCategory notificationsCategory = (PreferenceCategory) 518 findPreference(PREFERENCE_CATEGORY_NOTIFICATIONS); 519 notificationsCategory.removePreference(mAccountVibrateWhen); 520 } 521 522 findPreference(PREFERENCE_INCOMING).setOnPreferenceClickListener( 523 new Preference.OnPreferenceClickListener() { 524 public boolean onPreferenceClick(Preference preference) { 525 mAccountDirty = true; 526 mCallback.onIncomingSettings(mAccount); 527 return true; 528 } 529 }); 530 531 // Hide the outgoing account setup link if it's not activated 532 Preference prefOutgoing = findPreference(PREFERENCE_OUTGOING); 533 boolean showOutgoing = true; 534 try { 535 Sender sender = Sender.getInstance(mContext, mAccount); 536 if (sender != null) { 537 Class<? extends android.app.Activity> setting = sender.getSettingActivityClass(); 538 showOutgoing = (setting != null); 539 } 540 } catch (MessagingException me) { 541 // just leave showOutgoing as true - bias towards showing it, so user can fix it 542 } 543 if (showOutgoing) { 544 prefOutgoing.setOnPreferenceClickListener( 545 new Preference.OnPreferenceClickListener() { 546 public boolean onPreferenceClick(Preference preference) { 547 mAccountDirty = true; 548 mCallback.onOutgoingSettings(mAccount); 549 return true; 550 } 551 }); 552 } else { 553 PreferenceCategory serverCategory = (PreferenceCategory) findPreference( 554 PREFERENCE_CATEGORY_SERVER); 555 serverCategory.removePreference(prefOutgoing); 556 } 557 558 mSyncContacts = (CheckBoxPreference) findPreference(PREFERENCE_SYNC_CONTACTS); 559 mSyncCalendar = (CheckBoxPreference) findPreference(PREFERENCE_SYNC_CALENDAR); 560 mSyncEmail = (CheckBoxPreference) findPreference(PREFERENCE_SYNC_EMAIL); 561 if (mAccount.mHostAuthRecv.mProtocol.equals("eas")) { 562 android.accounts.Account acct = new android.accounts.Account(mAccount.mEmailAddress, 563 AccountManagerTypes.TYPE_EXCHANGE); 564 mSyncContacts.setChecked(ContentResolver 565 .getSyncAutomatically(acct, ContactsContract.AUTHORITY)); 566 mSyncContacts.setOnPreferenceChangeListener(mPreferenceChangeListener); 567 mSyncCalendar.setChecked(ContentResolver 568 .getSyncAutomatically(acct, CalendarProviderStub.AUTHORITY)); 569 mSyncCalendar.setOnPreferenceChangeListener(mPreferenceChangeListener); 570 mSyncEmail.setChecked(ContentResolver 571 .getSyncAutomatically(acct, EmailContent.AUTHORITY)); 572 mSyncEmail.setOnPreferenceChangeListener(mPreferenceChangeListener); 573 } else { 574 PreferenceCategory serverCategory = (PreferenceCategory) findPreference( 575 PREFERENCE_CATEGORY_SERVER); 576 serverCategory.removePreference(mSyncContacts); 577 serverCategory.removePreference(mSyncCalendar); 578 serverCategory.removePreference(mSyncEmail); 579 } 580 581 // Temporary home for delete account 582 Preference prefDeleteAccount = findPreference(PREFERENCE_DELETE_ACCOUNT); 583 prefDeleteAccount.setOnPreferenceClickListener( 584 new Preference.OnPreferenceClickListener() { 585 public boolean onPreferenceClick(Preference preference) { 586 DeleteAccountFragment dialogFragment = DeleteAccountFragment.newInstance( 587 mAccount, AccountSettingsFragment.this); 588 FragmentTransaction ft = getFragmentManager().beginTransaction(); 589 ft.addToBackStack(null); 590 dialogFragment.show(ft, DeleteAccountFragment.TAG); 591 return true; 592 } 593 }); 594 } 595 596 /** 597 * Generic onPreferenceChanged listener for the preferences (above) that just need 598 * to be written, without extra tweaks 599 */ 600 private final Preference.OnPreferenceChangeListener mPreferenceChangeListener = 601 new Preference.OnPreferenceChangeListener() { 602 public boolean onPreferenceChange(Preference preference, Object newValue) { 603 onPreferenceChanged(preference.getKey(), newValue); 604 return true; 605 } 606 }; 607 608 /** 609 * Called any time a preference is changed. 610 */ 611 private void onPreferenceChanged(String preference, Object value) { 612 mCallback.onSettingsChanged(mAccount, preference, value); 613 mSaveOnExit = true; 614 } 615 616 /* 617 * Note: This writes the settings on the UI thread. This has to be done so the settings are 618 * committed before we might be killed. 619 */ 620 private void saveSettings() { 621 // Turn off all controlled flags - will turn them back on while checking UI elements 622 int newFlags = mAccount.getFlags() & 623 ~(Account.FLAGS_NOTIFY_NEW_MAIL | 624 Account.FLAGS_VIBRATE_ALWAYS | Account.FLAGS_VIBRATE_WHEN_SILENT | 625 Account.FLAGS_BACKGROUND_ATTACHMENTS); 626 627 newFlags |= mAccountBackgroundAttachments.isChecked() ? 628 Account.FLAGS_BACKGROUND_ATTACHMENTS : 0; 629 mAccount.setDefaultAccount(mAccountDefault.isChecked()); 630 // If the display name has been cleared, we'll reset it to the default value (email addr) 631 mAccount.setDisplayName(mAccountDescription.getText().trim()); 632 // The sender name must never be empty (this is enforced by the preference editor) 633 mAccount.setSenderName(mAccountName.getText().trim()); 634 mAccount.setSignature(mAccountSignature.getText()); 635 newFlags |= mAccountNotify.isChecked() ? Account.FLAGS_NOTIFY_NEW_MAIL : 0; 636 mAccount.setSyncInterval(Integer.parseInt(mCheckFrequency.getValue())); 637 if (mSyncWindow != null) { 638 mAccount.setSyncLookback(Integer.parseInt(mSyncWindow.getValue())); 639 } 640 if (mAccountVibrateWhen.getValue().equals(PREFERENCE_VALUE_VIBRATE_WHEN_ALWAYS)) { 641 newFlags |= Account.FLAGS_VIBRATE_ALWAYS; 642 } else if (mAccountVibrateWhen.getValue().equals(PREFERENCE_VALUE_VIBRATE_WHEN_SILENT)) { 643 newFlags |= Account.FLAGS_VIBRATE_WHEN_SILENT; 644 } 645 SharedPreferences prefs = mAccountRingtone.getPreferenceManager().getSharedPreferences(); 646 mAccount.setRingtone(prefs.getString(PREFERENCE_RINGTONE, null)); 647 mAccount.setFlags(newFlags); 648 649 if (mAccount.mHostAuthRecv.mProtocol.equals("eas")) { 650 android.accounts.Account acct = new android.accounts.Account(mAccount.mEmailAddress, 651 AccountManagerTypes.TYPE_EXCHANGE); 652 ContentResolver.setSyncAutomatically(acct, ContactsContract.AUTHORITY, 653 mSyncContacts.isChecked()); 654 ContentResolver.setSyncAutomatically(acct, CalendarProviderStub.AUTHORITY, 655 mSyncCalendar.isChecked()); 656 ContentResolver.setSyncAutomatically(acct, EmailContent.AUTHORITY, 657 mSyncEmail.isChecked()); 658 } 659 660 // Commit the changes 661 // Note, this is done in the UI thread because at this point, we must commit 662 // all changes - any time after onPause completes, we could be killed. This is analogous 663 // to the way that SharedPreferences tries to work off-thread in apply(), but will pause 664 // until completion in onPause(). 665 ContentValues cv = AccountSettingsUtils.getAccountContentValues(mAccount); 666 mAccount.update(mContext, cv); 667 668 // Run the remaining changes off-thread 669 Email.setServicesEnabledAsync(mContext); 670 } 671 672 /** 673 * Dialog fragment to show "remove account?" dialog 674 */ 675 public static class DeleteAccountFragment extends DialogFragment { 676 private final static String TAG = "DeleteAccountFragment"; 677 678 // Argument bundle keys 679 private final static String BUNDLE_KEY_ACCOUNT_NAME = "DeleteAccountFragment.Name"; 680 681 /** 682 * Create the dialog with parameters 683 */ 684 public static DeleteAccountFragment newInstance(Account account, Fragment parentFragment) { 685 DeleteAccountFragment f = new DeleteAccountFragment(); 686 Bundle b = new Bundle(); 687 b.putString(BUNDLE_KEY_ACCOUNT_NAME, account.getDisplayName()); 688 f.setArguments(b); 689 f.setTargetFragment(parentFragment, 0); 690 return f; 691 } 692 693 @Override 694 public Dialog onCreateDialog(Bundle savedInstanceState) { 695 Context context = getActivity(); 696 final String name = getArguments().getString(BUNDLE_KEY_ACCOUNT_NAME); 697 698 return new AlertDialog.Builder(context) 699 .setIconAttribute(android.R.attr.alertDialogIcon) 700 .setTitle(R.string.account_delete_dlg_title) 701 .setMessage(context.getString(R.string.account_delete_dlg_instructions_fmt, name)) 702 .setPositiveButton( 703 R.string.okay_action, 704 new DialogInterface.OnClickListener() { 705 public void onClick(DialogInterface dialog, int whichButton) { 706 Fragment f = getTargetFragment(); 707 if (f instanceof AccountSettingsFragment) { 708 ((AccountSettingsFragment)f).finishDeleteAccount(); 709 } 710 dismiss(); 711 } 712 }) 713 .setNegativeButton( 714 R.string.cancel_action, 715 new DialogInterface.OnClickListener() { 716 public void onClick(DialogInterface dialog, int whichButton) { 717 dismiss(); 718 } 719 }) 720 .create(); 721 } 722 } 723 724 /** 725 * Callback from delete account dialog - passes the delete command up to the activity 726 */ 727 private void finishDeleteAccount() { 728 mSaveOnExit = false; 729 mCallback.deleteAccount(mAccount); 730 } 731 732 public String getAccountEmail() { 733 // Get the e-mail address of the account being editted, if this is for an existing account. 734 return mAccountEmail; 735 } 736} 737