1 /** 2 * Copyright (C) 2014 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 17 package com.android.phone.settings; 18 19 import android.app.Dialog; 20 import android.content.DialogInterface; 21 import android.content.Intent; 22 import android.database.Cursor; 23 import android.os.AsyncResult; 24 import android.os.Bundle; 25 import android.os.Handler; 26 import android.os.Message; 27 import android.os.PersistableBundle; 28 import android.os.UserManager; 29 import android.preference.Preference; 30 import android.preference.PreferenceActivity; 31 import android.preference.PreferenceScreen; 32 import android.preference.SwitchPreference; 33 import android.provider.ContactsContract.CommonDataKinds; 34 import android.provider.Settings; 35 import android.telecom.PhoneAccountHandle; 36 import android.telephony.CarrierConfigManager; 37 import android.telephony.TelephonyManager; 38 import android.text.BidiFormatter; 39 import android.text.TextDirectionHeuristics; 40 import android.text.TextUtils; 41 import android.util.Log; 42 import android.view.MenuItem; 43 import android.widget.ListAdapter; 44 import android.widget.Toast; 45 46 import com.android.internal.telephony.CallForwardInfo; 47 import com.android.internal.telephony.Phone; 48 import com.android.internal.telephony.PhoneConstants; 49 import com.android.internal.telephony.util.NotificationChannelController; 50 import com.android.phone.EditPhoneNumberPreference; 51 import com.android.phone.PhoneGlobals; 52 import com.android.phone.PhoneUtils; 53 import com.android.phone.R; 54 import com.android.phone.SubscriptionInfoHelper; 55 56 import java.util.Collection; 57 import java.util.HashMap; 58 import java.util.HashSet; 59 import java.util.Iterator; 60 import java.util.Map; 61 62 public class VoicemailSettingsActivity extends PreferenceActivity 63 implements DialogInterface.OnClickListener, 64 Preference.OnPreferenceChangeListener, 65 EditPhoneNumberPreference.OnDialogClosedListener, 66 EditPhoneNumberPreference.GetDefaultNumberListener{ 67 private static final String LOG_TAG = VoicemailSettingsActivity.class.getSimpleName(); 68 private static final boolean DBG = (PhoneGlobals.DBG_LEVEL >= 2); 69 70 /** 71 * Intent action to bring up Voicemail Provider settings 72 * DO NOT RENAME. There are existing apps which use this intent value. 73 */ 74 public static final String ACTION_ADD_VOICEMAIL = 75 "com.android.phone.CallFeaturesSetting.ADD_VOICEMAIL"; 76 77 /** 78 * Intent action to bring up the {@code VoicemailSettingsActivity}. 79 * DO NOT RENAME. There are existing apps which use this intent value. 80 */ 81 public static final String ACTION_CONFIGURE_VOICEMAIL = 82 "com.android.phone.CallFeaturesSetting.CONFIGURE_VOICEMAIL"; 83 84 // Extra put in the return from VM provider config containing voicemail number to set 85 public static final String VM_NUMBER_EXTRA = "com.android.phone.VoicemailNumber"; 86 // Extra put in the return from VM provider config containing call forwarding number to set 87 public static final String FWD_NUMBER_EXTRA = "com.android.phone.ForwardingNumber"; 88 // Extra put in the return from VM provider config containing call forwarding number to set 89 public static final String FWD_NUMBER_TIME_EXTRA = "com.android.phone.ForwardingNumberTime"; 90 // If the VM provider returns non null value in this extra we will force the user to 91 // choose another VM provider 92 public static final String SIGNOUT_EXTRA = "com.android.phone.Signout"; 93 94 /** 95 * String Extra put into ACTION_ADD_VOICEMAIL call to indicate which provider should be hidden 96 * in the list of providers presented to the user. This allows a provider which is being 97 * disabled (e.g. GV user logging out) to force the user to pick some other provider. 98 */ 99 public static final String IGNORE_PROVIDER_EXTRA = "com.android.phone.ProviderToIgnore"; 100 101 /** 102 * String Extra put into ACTION_ADD_VOICEMAIL to indicate that the voicemail setup screen should 103 * be opened. 104 */ 105 public static final String SETUP_VOICEMAIL_EXTRA = "com.android.phone.SetupVoicemail"; 106 107 // TODO: Define these preference keys in XML. 108 private static final String BUTTON_VOICEMAIL_KEY = "button_voicemail_key"; 109 private static final String BUTTON_VOICEMAIL_PROVIDER_KEY = "button_voicemail_provider_key"; 110 private static final String BUTTON_VOICEMAIL_SETTING_KEY = "button_voicemail_setting_key"; 111 112 /** Event for Async voicemail change call */ 113 private static final int EVENT_VOICEMAIL_CHANGED = 500; 114 private static final int EVENT_FORWARDING_CHANGED = 501; 115 private static final int EVENT_FORWARDING_GET_COMPLETED = 502; 116 117 /** Handle to voicemail pref */ 118 private static final int VOICEMAIL_PREF_ID = 1; 119 private static final int VOICEMAIL_PROVIDER_CFG_ID = 2; 120 121 /** 122 * Results of reading forwarding settings 123 */ 124 private CallForwardInfo[] mForwardingReadResults = null; 125 126 /** 127 * Result of forwarding number change. 128 * Keys are reasons (eg. unconditional forwarding). 129 */ 130 private Map<Integer, AsyncResult> mForwardingChangeResults = null; 131 132 /** 133 * Expected CF read result types. 134 * This set keeps track of the CF types for which we've issued change 135 * commands so we can tell when we've received all of the responses. 136 */ 137 private Collection<Integer> mExpectedChangeResultReasons = null; 138 139 /** 140 * Result of vm number change 141 */ 142 private AsyncResult mVoicemailChangeResult = null; 143 144 /** 145 * Previous VM provider setting so we can return to it in case of failure. 146 */ 147 private String mPreviousVMProviderKey = null; 148 149 /** 150 * Id of the dialog being currently shown. 151 */ 152 private int mCurrentDialogId = 0; 153 154 /** 155 * Flag indicating that we are invoking settings for the voicemail provider programmatically 156 * due to vm provider change. 157 */ 158 private boolean mVMProviderSettingsForced = false; 159 160 /** 161 * Flag indicating that we are making changes to vm or fwd numbers 162 * due to vm provider change. 163 */ 164 private boolean mChangingVMorFwdDueToProviderChange = false; 165 166 /** 167 * True if we are in the process of vm & fwd number change and vm has already been changed. 168 * This is used to decide what to do in case of rollback. 169 */ 170 private boolean mVMChangeCompletedSuccessfully = false; 171 172 /** 173 * True if we had full or partial failure setting forwarding numbers and so need to roll them 174 * back. 175 */ 176 private boolean mFwdChangesRequireRollback = false; 177 178 /** 179 * Id of error msg to display to user once we are done reverting the VM provider to the previous 180 * one. 181 */ 182 private int mVMOrFwdSetError = 0; 183 184 /** string to hold old voicemail number as it is being updated. */ 185 private String mOldVmNumber; 186 187 // New call forwarding settings and vm number we will be setting 188 // Need to save these since before we get to saving we need to asynchronously 189 // query the existing forwarding settings. 190 private CallForwardInfo[] mNewFwdSettings; 191 private String mNewVMNumber; 192 193 /** 194 * Used to indicate that the voicemail preference should be shown. 195 */ 196 private boolean mShowVoicemailPreference = false; 197 198 private boolean mForeground; 199 private Phone mPhone; 200 private SubscriptionInfoHelper mSubscriptionInfoHelper; 201 202 private EditPhoneNumberPreference mSubMenuVoicemailSettings = null; 203 private VoicemailProviderListPreference mVoicemailProviders; 204 private PreferenceScreen mVoicemailSettings; 205 private Preference mVoicemailNotificationPreference; 206 207 //********************************************************************************************* 208 // Preference Activity Methods 209 //********************************************************************************************* 210 211 @Override 212 protected void onCreate(Bundle icicle) { 213 super.onCreate(icicle); 214 // Make sure we are running as the primary user only 215 UserManager userManager = getApplicationContext().getSystemService(UserManager.class); 216 if (!userManager.isPrimaryUser()) { 217 Toast.makeText(this, R.string.voice_number_setting_primary_user_only, 218 Toast.LENGTH_SHORT).show(); 219 finish(); 220 return; 221 } 222 // Show the voicemail preference in onResume if the calling intent specifies the 223 // ACTION_ADD_VOICEMAIL action. 224 mShowVoicemailPreference = (icicle == null) && 225 TextUtils.equals(getIntent().getAction(), ACTION_ADD_VOICEMAIL); 226 227 PhoneAccountHandle phoneAccountHandle = (PhoneAccountHandle) 228 getIntent().getParcelableExtra(TelephonyManager.EXTRA_PHONE_ACCOUNT_HANDLE); 229 if (phoneAccountHandle != null) { 230 getIntent().putExtra(SubscriptionInfoHelper.SUB_ID_EXTRA, 231 PhoneUtils.getSubIdForPhoneAccountHandle(phoneAccountHandle)); 232 } 233 mSubscriptionInfoHelper = new SubscriptionInfoHelper(this, getIntent()); 234 mSubscriptionInfoHelper.setActionBarTitle( 235 getActionBar(), getResources(), R.string.voicemail_settings_with_label); 236 mPhone = mSubscriptionInfoHelper.getPhone(); 237 addPreferencesFromResource(R.xml.voicemail_settings); 238 239 mVoicemailNotificationPreference = 240 findPreference(getString(R.string.voicemail_notifications_key)); 241 final Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS); 242 intent.putExtra(Settings.EXTRA_CHANNEL_ID, 243 NotificationChannelController.CHANNEL_ID_VOICE_MAIL); 244 intent.putExtra(Settings.EXTRA_APP_PACKAGE, mPhone.getContext().getPackageName()); 245 mVoicemailNotificationPreference.setIntent(intent); 246 } 247 248 @Override 249 protected void onResume() { 250 super.onResume(); 251 mForeground = true; 252 253 PreferenceScreen prefSet = getPreferenceScreen(); 254 255 if (mSubMenuVoicemailSettings == null) { 256 mSubMenuVoicemailSettings = 257 (EditPhoneNumberPreference) findPreference(BUTTON_VOICEMAIL_KEY); 258 } 259 if (mSubMenuVoicemailSettings != null) { 260 mSubMenuVoicemailSettings.setParentActivity(this, VOICEMAIL_PREF_ID, this); 261 mSubMenuVoicemailSettings.setDialogOnClosedListener(this); 262 mSubMenuVoicemailSettings.setDialogTitle(R.string.voicemail_settings_number_label); 263 if (!getBooleanCarrierConfig( 264 CarrierConfigManager.KEY_EDITABLE_VOICEMAIL_NUMBER_SETTING_BOOL)) { 265 mSubMenuVoicemailSettings.setEnabled(false); 266 } 267 } 268 269 mVoicemailProviders = (VoicemailProviderListPreference) findPreference( 270 BUTTON_VOICEMAIL_PROVIDER_KEY); 271 mVoicemailProviders.init(mPhone, getIntent()); 272 mVoicemailProviders.setOnPreferenceChangeListener(this); 273 mPreviousVMProviderKey = mVoicemailProviders.getValue(); 274 275 mVoicemailSettings = (PreferenceScreen) findPreference(BUTTON_VOICEMAIL_SETTING_KEY); 276 277 maybeHidePublicSettings(); 278 279 updateVMPreferenceWidgets(mVoicemailProviders.getValue()); 280 281 // check the intent that started this activity and pop up the voicemail 282 // dialog if we've been asked to. 283 // If we have at least one non default VM provider registered then bring up 284 // the selection for the VM provider, otherwise bring up a VM number dialog. 285 // We only bring up the dialog the first time we are called (not after orientation change) 286 if (mShowVoicemailPreference) { 287 if (DBG) log("ACTION_ADD_VOICEMAIL Intent is thrown"); 288 if (mVoicemailProviders.hasMoreThanOneVoicemailProvider()) { 289 if (DBG) log("Voicemail data has more than one provider."); 290 simulatePreferenceClick(mVoicemailProviders); 291 } else { 292 onPreferenceChange(mVoicemailProviders, VoicemailProviderListPreference.DEFAULT_KEY); 293 mVoicemailProviders.setValue(VoicemailProviderListPreference.DEFAULT_KEY); 294 } 295 mShowVoicemailPreference = false; 296 } 297 298 updateVoiceNumberField(); 299 mVMProviderSettingsForced = false; 300 } 301 302 /** 303 * Hides a subset of voicemail settings if required by the intent extra. This is used by the 304 * default dialer to show "advanced" voicemail settings from its own custom voicemail settings 305 * UI. 306 */ 307 private void maybeHidePublicSettings() { 308 if(!getIntent().getBooleanExtra(TelephonyManager.EXTRA_HIDE_PUBLIC_SETTINGS, false)){ 309 return; 310 } 311 if (DBG) { 312 log("maybeHidePublicSettings: settings hidden by EXTRA_HIDE_PUBLIC_SETTINGS"); 313 } 314 PreferenceScreen preferenceScreen = getPreferenceScreen(); 315 preferenceScreen.removePreference(mVoicemailNotificationPreference); 316 } 317 318 @Override 319 public void onPause() { 320 super.onPause(); 321 mForeground = false; 322 } 323 324 @Override 325 public boolean onOptionsItemSelected(MenuItem item) { 326 if (item.getItemId() == android.R.id.home) { 327 onBackPressed(); 328 return true; 329 } 330 return super.onOptionsItemSelected(item); 331 } 332 333 @Override 334 public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { 335 if (preference == mSubMenuVoicemailSettings) { 336 return true; 337 } else if (preference.getKey().equals(mVoicemailSettings.getKey())) { 338 // Check key instead of comparing reference because closing the voicemail notification 339 // ringtone dialog invokes onResume(), but leaves the old preference screen up, 340 // TODO: Revert to checking reference after migrating voicemail to its own activity. 341 if (DBG) log("onPreferenceTreeClick: Voicemail Settings Preference is clicked."); 342 343 final Dialog dialog = ((PreferenceScreen) preference).getDialog(); 344 if (dialog != null) { 345 dialog.getActionBar().setDisplayHomeAsUpEnabled(false); 346 } 347 348 mSubMenuVoicemailSettings = 349 (EditPhoneNumberPreference) findPreference(BUTTON_VOICEMAIL_KEY); 350 mSubMenuVoicemailSettings.setParentActivity(this, VOICEMAIL_PREF_ID, this); 351 mSubMenuVoicemailSettings.setDialogOnClosedListener(this); 352 mSubMenuVoicemailSettings.setDialogTitle(R.string.voicemail_settings_number_label); 353 updateVoiceNumberField(); 354 355 if (preference.getIntent() != null) { 356 if (DBG) log("Invoking cfg intent " + preference.getIntent().getPackage()); 357 358 // onActivityResult() will be responsible for resetting some of variables. 359 this.startActivityForResult(preference.getIntent(), VOICEMAIL_PROVIDER_CFG_ID); 360 return true; 361 } else { 362 if (DBG) log("onPreferenceTreeClick(). No intent; use default behavior in xml."); 363 364 // onActivityResult() will not be called, so reset variables here. 365 mPreviousVMProviderKey = VoicemailProviderListPreference.DEFAULT_KEY; 366 mVMProviderSettingsForced = false; 367 return false; 368 } 369 } 370 return false; 371 } 372 373 /** 374 * Implemented to support onPreferenceChangeListener to look for preference changes. 375 * 376 * @param preference is the preference to be changed 377 * @param objValue should be the value of the selection, NOT its localized 378 * display value. 379 */ 380 @Override 381 public boolean onPreferenceChange(Preference preference, Object objValue) { 382 if (DBG) log("onPreferenceChange: \"" + preference + "\" changed to \"" + objValue + "\""); 383 384 if (preference == mVoicemailProviders) { 385 final String newProviderKey = (String) objValue; 386 387 // If previous provider key and the new one is same, we don't need to handle it. 388 if (mPreviousVMProviderKey.equals(newProviderKey)) { 389 if (DBG) log("No change is made to the VM provider setting."); 390 return true; 391 } 392 updateVMPreferenceWidgets(newProviderKey); 393 394 final VoicemailProviderSettings newProviderSettings = 395 VoicemailProviderSettingsUtil.load(this, newProviderKey); 396 397 // If the user switches to a voice mail provider and we have numbers stored for it we 398 // will automatically change the phone's voice mail and forwarding number to the stored 399 // ones. Otherwise we will bring up provider's configuration UI. 400 if (newProviderSettings == null) { 401 // Force the user into a configuration of the chosen provider 402 Log.w(LOG_TAG, "Saved preferences not found - invoking config"); 403 mVMProviderSettingsForced = true; 404 simulatePreferenceClick(mVoicemailSettings); 405 } else { 406 if (DBG) log("Saved preferences found - switching to them"); 407 // Set this flag so if we get a failure we revert to previous provider 408 mChangingVMorFwdDueToProviderChange = true; 409 saveVoiceMailAndForwardingNumber(newProviderKey, newProviderSettings); 410 } 411 } 412 // Always let the preference setting proceed. 413 return true; 414 } 415 416 /** 417 * Implemented for EditPhoneNumberPreference.GetDefaultNumberListener. 418 * This method set the default values for the various 419 * EditPhoneNumberPreference dialogs. 420 */ 421 @Override 422 public String onGetDefaultNumber(EditPhoneNumberPreference preference) { 423 if (preference == mSubMenuVoicemailSettings) { 424 // update the voicemail number field, which takes care of the 425 // mSubMenuVoicemailSettings itself, so we should return null. 426 if (DBG) log("updating default for voicemail dialog"); 427 updateVoiceNumberField(); 428 return null; 429 } 430 431 String vmDisplay = mPhone.getVoiceMailNumber(); 432 if (TextUtils.isEmpty(vmDisplay)) { 433 // if there is no voicemail number, we just return null to 434 // indicate no contribution. 435 return null; 436 } 437 438 // Return the voicemail number prepended with "VM: " 439 if (DBG) log("updating default for call forwarding dialogs"); 440 return getString(R.string.voicemail_abbreviated) + " " + vmDisplay; 441 } 442 443 @Override 444 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 445 if (DBG) { 446 log("onActivityResult: requestCode: " + requestCode 447 + ", resultCode: " + resultCode 448 + ", data: " + data); 449 } 450 451 // there are cases where the contact picker may end up sending us more than one 452 // request. We want to ignore the request if we're not in the correct state. 453 if (requestCode == VOICEMAIL_PROVIDER_CFG_ID) { 454 boolean failure = false; 455 456 // No matter how the processing of result goes lets clear the flag 457 if (DBG) log("mVMProviderSettingsForced: " + mVMProviderSettingsForced); 458 final boolean isVMProviderSettingsForced = mVMProviderSettingsForced; 459 mVMProviderSettingsForced = false; 460 461 String vmNum = null; 462 if (resultCode != RESULT_OK) { 463 if (DBG) log("onActivityResult: vm provider cfg result not OK."); 464 failure = true; 465 } else { 466 if (data == null) { 467 if (DBG) log("onActivityResult: vm provider cfg result has no data"); 468 failure = true; 469 } else { 470 if (data.getBooleanExtra(SIGNOUT_EXTRA, false)) { 471 if (DBG) log("Provider requested signout"); 472 if (isVMProviderSettingsForced) { 473 if (DBG) log("Going back to previous provider on signout"); 474 switchToPreviousVoicemailProvider(); 475 } else { 476 final String victim = mVoicemailProviders.getKey(); 477 if (DBG) log("Relaunching activity and ignoring " + victim); 478 Intent i = new Intent(ACTION_ADD_VOICEMAIL); 479 i.putExtra(IGNORE_PROVIDER_EXTRA, victim); 480 i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 481 this.startActivity(i); 482 } 483 return; 484 } 485 vmNum = data.getStringExtra(VM_NUMBER_EXTRA); 486 if (vmNum == null || vmNum.length() == 0) { 487 if (DBG) log("onActivityResult: vm provider cfg result has no vmnum"); 488 failure = true; 489 } 490 } 491 } 492 if (failure) { 493 if (DBG) log("Failure in return from voicemail provider."); 494 if (isVMProviderSettingsForced) { 495 switchToPreviousVoicemailProvider(); 496 } 497 498 return; 499 } 500 mChangingVMorFwdDueToProviderChange = isVMProviderSettingsForced; 501 final String fwdNum = data.getStringExtra(FWD_NUMBER_EXTRA); 502 503 // TODO: It would be nice to load the current network setting for this and 504 // send it to the provider when it's config is invoked so it can use this as default 505 final int fwdNumTime = data.getIntExtra(FWD_NUMBER_TIME_EXTRA, 20); 506 507 if (DBG) log("onActivityResult: cfg result has forwarding number " + fwdNum); 508 saveVoiceMailAndForwardingNumber(mVoicemailProviders.getKey(), 509 new VoicemailProviderSettings(vmNum, fwdNum, fwdNumTime)); 510 return; 511 } 512 513 if (requestCode == VOICEMAIL_PREF_ID) { 514 if (resultCode != RESULT_OK) { 515 if (DBG) log("onActivityResult: contact picker result not OK."); 516 return; 517 } 518 519 Cursor cursor = null; 520 try { 521 cursor = getContentResolver().query(data.getData(), 522 new String[] { CommonDataKinds.Phone.NUMBER }, null, null, null); 523 if ((cursor == null) || (!cursor.moveToFirst())) { 524 if (DBG) log("onActivityResult: bad contact data, no results found."); 525 return; 526 } 527 if (mSubMenuVoicemailSettings != null) { 528 mSubMenuVoicemailSettings.onPickActivityResult(cursor.getString(0)); 529 } else { 530 Log.w(LOG_TAG, "VoicemailSettingsActivity destroyed while setting contacts."); 531 } 532 return; 533 } finally { 534 if (cursor != null) { 535 cursor.close(); 536 } 537 } 538 } 539 540 super.onActivityResult(requestCode, resultCode, data); 541 } 542 543 /** 544 * Simulates user clicking on a passed preference. 545 * Usually needed when the preference is a dialog preference and we want to invoke 546 * a dialog for this preference programmatically. 547 * TODO: figure out if there is a cleaner way to cause preference dlg to come up 548 */ 549 private void simulatePreferenceClick(Preference preference) { 550 // Go through settings until we find our setting 551 // and then simulate a click on it to bring up the dialog 552 final ListAdapter adapter = getPreferenceScreen().getRootAdapter(); 553 for (int idx = 0; idx < adapter.getCount(); idx++) { 554 if (adapter.getItem(idx) == preference) { 555 getPreferenceScreen().onItemClick(this.getListView(), 556 null, idx, adapter.getItemId(idx)); 557 break; 558 } 559 } 560 } 561 562 /** 563 * Get the boolean config from carrier config manager. 564 * 565 * @param key config key defined in CarrierConfigManager 566 * @return boolean value of corresponding key. 567 */ 568 private boolean getBooleanCarrierConfig(String key) { 569 PersistableBundle b = PhoneGlobals.getInstance() 570 .getCarrierConfigForSubId(mPhone.getSubId()); 571 if (b != null) { 572 return b.getBoolean(key); 573 } else { 574 // Return static default defined in CarrierConfigManager. 575 return CarrierConfigManager.getDefaultConfig().getBoolean(key); 576 } 577 } 578 579 580 //********************************************************************************************* 581 // Activity Dialog Methods 582 //********************************************************************************************* 583 584 @Override 585 protected void onPrepareDialog(int id, Dialog dialog) { 586 super.onPrepareDialog(id, dialog); 587 mCurrentDialogId = id; 588 } 589 590 // dialog creation method, called by showDialog() 591 @Override 592 protected Dialog onCreateDialog(int dialogId) { 593 return VoicemailDialogUtil.getDialog(this, dialogId); 594 } 595 596 @Override 597 public void onDialogClosed(EditPhoneNumberPreference preference, int buttonClicked) { 598 if (DBG) log("onDialogClosed: Button clicked is " + buttonClicked); 599 600 if (buttonClicked == DialogInterface.BUTTON_NEGATIVE) { 601 return; 602 } 603 604 if (preference == mSubMenuVoicemailSettings) { 605 VoicemailProviderSettings newSettings = new VoicemailProviderSettings( 606 mSubMenuVoicemailSettings.getPhoneNumber(), 607 VoicemailProviderSettings.NO_FORWARDING); 608 saveVoiceMailAndForwardingNumber(mVoicemailProviders.getKey(), newSettings); 609 } 610 } 611 612 /** 613 * Wrapper around showDialog() that will silently do nothing if we're 614 * not in the foreground. 615 * 616 * This is useful here because most of the dialogs we display from 617 * this class are triggered by asynchronous events (like 618 * success/failure messages from the telephony layer) and it's 619 * possible for those events to come in even after the user has gone 620 * to a different screen. 621 */ 622 // TODO: this is too brittle: it's still easy to accidentally add new 623 // code here that calls showDialog() directly (which will result in a 624 // WindowManager$BadTokenException if called after the activity has 625 // been stopped.) 626 // 627 // It would be cleaner to do the "if (mForeground)" check in one 628 // central place, maybe by using a single Handler for all asynchronous 629 // events (and have *that* discard events if we're not in the 630 // foreground.) 631 // 632 // Unfortunately it's not that simple, since we sometimes need to do 633 // actual work to handle these events whether or not we're in the 634 // foreground (see the Handler code in mSetOptionComplete for 635 // example.) 636 // 637 // TODO: It's a bit worrisome that we don't do anything in error cases when we're not in the 638 // foreground. Consider displaying a toast instead. 639 private void showDialogIfForeground(int id) { 640 if (mForeground) { 641 showDialog(id); 642 } 643 } 644 645 private void dismissDialogSafely(int id) { 646 try { 647 dismissDialog(id); 648 } catch (IllegalArgumentException e) { 649 // This is expected in the case where we were in the background 650 // at the time we would normally have shown the dialog, so we didn't 651 // show it. 652 } 653 } 654 655 // This is a method implemented for DialogInterface.OnClickListener. 656 // Used with the error dialog to close the app, voicemail dialog to just dismiss. 657 // Close button is mapped to BUTTON_POSITIVE for the errors that close the activity, 658 // while those that are mapped to BUTTON_NEUTRAL only move the preference focus. 659 public void onClick(DialogInterface dialog, int which) { 660 if (DBG) log("onClick: button clicked is " + which); 661 662 dialog.dismiss(); 663 switch (which){ 664 case DialogInterface.BUTTON_NEGATIVE: 665 if (mCurrentDialogId == VoicemailDialogUtil.FWD_GET_RESPONSE_ERROR_DIALOG) { 666 // We failed to get current forwarding settings and the user 667 // does not wish to continue. 668 switchToPreviousVoicemailProvider(); 669 } 670 break; 671 case DialogInterface.BUTTON_POSITIVE: 672 if (mCurrentDialogId == VoicemailDialogUtil.FWD_GET_RESPONSE_ERROR_DIALOG) { 673 // We failed to get current forwarding settings but the user 674 // wishes to continue changing settings to the new vm provider 675 setVoicemailNumberWithCarrier(); 676 } else { 677 finish(); 678 } 679 return; 680 default: 681 // just let the dialog close and go back to the input 682 } 683 684 // In all dialogs, all buttons except BUTTON_POSITIVE lead to the end of user interaction 685 // with settings UI. If we were called to explicitly configure voice mail then 686 // we finish the settings activity here to come back to whatever the user was doing. 687 final String action = getIntent() != null ? getIntent().getAction() : null; 688 if (ACTION_ADD_VOICEMAIL.equals(action)) { 689 finish(); 690 } 691 } 692 693 694 //********************************************************************************************* 695 // Voicemail Methods 696 //********************************************************************************************* 697 698 /** 699 * TODO: Refactor to make it easier to understand what's done in the different stages. 700 */ 701 private void saveVoiceMailAndForwardingNumber( 702 String key, VoicemailProviderSettings newSettings) { 703 if (DBG) log("saveVoiceMailAndForwardingNumber: " + newSettings.toString()); 704 mNewVMNumber = newSettings.getVoicemailNumber(); 705 mNewVMNumber = (mNewVMNumber == null) ? "" : mNewVMNumber; 706 mNewFwdSettings = newSettings.getForwardingSettings(); 707 708 // Call forwarding is not suppported on CDMA. 709 if (mPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) { 710 if (DBG) log("Ignoring forwarding setting since this is CDMA phone"); 711 mNewFwdSettings = VoicemailProviderSettings.NO_FORWARDING; 712 } 713 714 // Throw a warning if the voicemail is the same and we did not change forwarding. 715 if (mNewVMNumber.equals(mOldVmNumber) 716 && mNewFwdSettings == VoicemailProviderSettings.NO_FORWARDING) { 717 showDialogIfForeground(VoicemailDialogUtil.VM_NOCHANGE_ERROR_DIALOG); 718 return; 719 } 720 721 VoicemailProviderSettingsUtil.save(this, key, newSettings); 722 mVMChangeCompletedSuccessfully = false; 723 mFwdChangesRequireRollback = false; 724 mVMOrFwdSetError = 0; 725 726 if (mNewFwdSettings == VoicemailProviderSettings.NO_FORWARDING 727 || key.equals(mPreviousVMProviderKey)) { 728 if (DBG) log("Set voicemail number. No changes to forwarding number."); 729 setVoicemailNumberWithCarrier(); 730 } else { 731 if (DBG) log("Reading current forwarding settings."); 732 int numSettingsReasons = VoicemailProviderSettings.FORWARDING_SETTINGS_REASONS.length; 733 mForwardingReadResults = new CallForwardInfo[numSettingsReasons]; 734 for (int i = 0; i < mForwardingReadResults.length; i++) { 735 mPhone.getCallForwardingOption( 736 VoicemailProviderSettings.FORWARDING_SETTINGS_REASONS[i], 737 mGetOptionComplete.obtainMessage(EVENT_FORWARDING_GET_COMPLETED, i, 0)); 738 } 739 showDialogIfForeground(VoicemailDialogUtil.VM_FWD_READING_DIALOG); 740 } 741 } 742 743 private final Handler mGetOptionComplete = new Handler() { 744 @Override 745 public void handleMessage(Message msg) { 746 AsyncResult result = (AsyncResult) msg.obj; 747 switch (msg.what) { 748 case EVENT_FORWARDING_GET_COMPLETED: 749 handleForwardingSettingsReadResult(result, msg.arg1); 750 break; 751 } 752 } 753 }; 754 755 private void handleForwardingSettingsReadResult(AsyncResult ar, int idx) { 756 if (DBG) Log.d(LOG_TAG, "handleForwardingSettingsReadResult: " + idx); 757 758 Throwable error = null; 759 if (ar.exception != null) { 760 error = ar.exception; 761 if (DBG) Log.d(LOG_TAG, "FwdRead: ar.exception=" + error.getMessage()); 762 } 763 if (ar.userObj instanceof Throwable) { 764 error = (Throwable) ar.userObj; 765 if (DBG) Log.d(LOG_TAG, "FwdRead: userObj=" + error.getMessage()); 766 } 767 768 // We may have already gotten an error and decided to ignore the other results. 769 if (mForwardingReadResults == null) { 770 if (DBG) Log.d(LOG_TAG, "Ignoring fwd reading result: " + idx); 771 return; 772 } 773 774 // In case of error ignore other results, show an error dialog 775 if (error != null) { 776 if (DBG) Log.d(LOG_TAG, "Error discovered for fwd read : " + idx); 777 mForwardingReadResults = null; 778 dismissDialogSafely(VoicemailDialogUtil.VM_FWD_READING_DIALOG); 779 showDialogIfForeground(VoicemailDialogUtil.FWD_GET_RESPONSE_ERROR_DIALOG); 780 return; 781 } 782 783 // Get the forwarding info. 784 mForwardingReadResults[idx] = CallForwardInfoUtil.getCallForwardInfo( 785 (CallForwardInfo[]) ar.result, 786 VoicemailProviderSettings.FORWARDING_SETTINGS_REASONS[idx]); 787 788 // Check if we got all the results already 789 boolean done = true; 790 for (int i = 0; i < mForwardingReadResults.length; i++) { 791 if (mForwardingReadResults[i] == null) { 792 done = false; 793 break; 794 } 795 } 796 797 if (done) { 798 if (DBG) Log.d(LOG_TAG, "Done receiving fwd info"); 799 dismissDialogSafely(VoicemailDialogUtil.VM_FWD_READING_DIALOG); 800 801 if (mPreviousVMProviderKey.equals(VoicemailProviderListPreference.DEFAULT_KEY)) { 802 VoicemailProviderSettingsUtil.save(mPhone.getContext(), 803 VoicemailProviderListPreference.DEFAULT_KEY, 804 new VoicemailProviderSettings(mOldVmNumber, mForwardingReadResults)); 805 } 806 saveVoiceMailAndForwardingNumberStage2(); 807 } 808 } 809 810 private void resetForwardingChangeState() { 811 mForwardingChangeResults = new HashMap<Integer, AsyncResult>(); 812 mExpectedChangeResultReasons = new HashSet<Integer>(); 813 } 814 815 // Called after we are done saving the previous forwarding settings if we needed. 816 private void saveVoiceMailAndForwardingNumberStage2() { 817 mForwardingChangeResults = null; 818 mVoicemailChangeResult = null; 819 820 resetForwardingChangeState(); 821 for (int i = 0; i < mNewFwdSettings.length; i++) { 822 CallForwardInfo fi = mNewFwdSettings[i]; 823 CallForwardInfo fiForReason = 824 CallForwardInfoUtil.infoForReason(mForwardingReadResults, fi.reason); 825 final boolean doUpdate = CallForwardInfoUtil.isUpdateRequired(fiForReason, fi); 826 827 if (doUpdate) { 828 if (DBG) log("Setting fwd #: " + i + ": " + fi.toString()); 829 mExpectedChangeResultReasons.add(i); 830 831 CallForwardInfoUtil.setCallForwardingOption(mPhone, fi, 832 mSetOptionComplete.obtainMessage( 833 EVENT_FORWARDING_CHANGED, fi.reason, 0)); 834 } 835 } 836 showDialogIfForeground(VoicemailDialogUtil.VM_FWD_SAVING_DIALOG); 837 } 838 839 840 /** 841 * Callback to handle option update completions 842 */ 843 private final Handler mSetOptionComplete = new Handler() { 844 @Override 845 public void handleMessage(Message msg) { 846 AsyncResult result = (AsyncResult) msg.obj; 847 boolean done = false; 848 switch (msg.what) { 849 case EVENT_VOICEMAIL_CHANGED: 850 mVoicemailChangeResult = result; 851 mVMChangeCompletedSuccessfully = isVmChangeSuccess(); 852 PhoneGlobals.getInstance().refreshMwiIndicator( 853 mSubscriptionInfoHelper.getSubId()); 854 done = true; 855 break; 856 case EVENT_FORWARDING_CHANGED: 857 mForwardingChangeResults.put(msg.arg1, result); 858 if (result.exception != null) { 859 Log.w(LOG_TAG, "Error in setting fwd# " + msg.arg1 + ": " + 860 result.exception.getMessage()); 861 } 862 if (isForwardingCompleted()) { 863 if (isFwdChangeSuccess()) { 864 if (DBG) log("Overall fwd changes completed ok, starting vm change"); 865 setVoicemailNumberWithCarrier(); 866 } else { 867 Log.w(LOG_TAG, "Overall fwd changes completed in failure. " + 868 "Check if we need to try rollback for some settings."); 869 mFwdChangesRequireRollback = false; 870 Iterator<Map.Entry<Integer,AsyncResult>> it = 871 mForwardingChangeResults.entrySet().iterator(); 872 while (it.hasNext()) { 873 Map.Entry<Integer,AsyncResult> entry = it.next(); 874 if (entry.getValue().exception == null) { 875 // If at least one succeeded we have to revert 876 Log.i(LOG_TAG, "Rollback will be required"); 877 mFwdChangesRequireRollback = true; 878 break; 879 } 880 } 881 if (!mFwdChangesRequireRollback) { 882 Log.i(LOG_TAG, "No rollback needed."); 883 } 884 done = true; 885 } 886 } 887 break; 888 default: 889 // TODO: should never reach this, may want to throw exception 890 } 891 892 if (done) { 893 if (DBG) log("All VM provider related changes done"); 894 if (mForwardingChangeResults != null) { 895 dismissDialogSafely(VoicemailDialogUtil.VM_FWD_SAVING_DIALOG); 896 } 897 handleSetVmOrFwdMessage(); 898 } 899 } 900 }; 901 902 /** 903 * Callback to handle option revert completions 904 */ 905 private final Handler mRevertOptionComplete = new Handler() { 906 @Override 907 public void handleMessage(Message msg) { 908 AsyncResult result = (AsyncResult) msg.obj; 909 switch (msg.what) { 910 case EVENT_VOICEMAIL_CHANGED: 911 if (DBG) log("VM revert complete msg"); 912 mVoicemailChangeResult = result; 913 break; 914 915 case EVENT_FORWARDING_CHANGED: 916 if (DBG) log("FWD revert complete msg "); 917 mForwardingChangeResults.put(msg.arg1, result); 918 if (result.exception != null) { 919 if (DBG) log("Error in reverting fwd# " + msg.arg1 + ": " + 920 result.exception.getMessage()); 921 } 922 break; 923 924 default: 925 // TODO: should never reach this, may want to throw exception 926 } 927 928 final boolean done = (!mVMChangeCompletedSuccessfully || mVoicemailChangeResult != null) 929 && (!mFwdChangesRequireRollback || isForwardingCompleted()); 930 if (done) { 931 if (DBG) log("All VM reverts done"); 932 dismissDialogSafely(VoicemailDialogUtil.VM_REVERTING_DIALOG); 933 onRevertDone(); 934 } 935 } 936 }; 937 938 private void setVoicemailNumberWithCarrier() { 939 if (DBG) log("save voicemail #: " + mNewVMNumber); 940 941 mVoicemailChangeResult = null; 942 mPhone.setVoiceMailNumber( 943 mPhone.getVoiceMailAlphaTag().toString(), 944 mNewVMNumber, 945 Message.obtain(mSetOptionComplete, EVENT_VOICEMAIL_CHANGED)); 946 } 947 948 private void switchToPreviousVoicemailProvider() { 949 if (DBG) log("switchToPreviousVoicemailProvider " + mPreviousVMProviderKey); 950 951 if (mPreviousVMProviderKey == null) { 952 return; 953 } 954 955 if (mVMChangeCompletedSuccessfully || mFwdChangesRequireRollback) { 956 showDialogIfForeground(VoicemailDialogUtil.VM_REVERTING_DIALOG); 957 final VoicemailProviderSettings prevSettings = 958 VoicemailProviderSettingsUtil.load(this, mPreviousVMProviderKey); 959 if (prevSettings == null) { 960 Log.e(LOG_TAG, "VoicemailProviderSettings for the key \"" 961 + mPreviousVMProviderKey + "\" is null but should be loaded."); 962 return; 963 } 964 965 if (mVMChangeCompletedSuccessfully) { 966 mNewVMNumber = prevSettings.getVoicemailNumber(); 967 Log.i(LOG_TAG, "VM change is already completed successfully." 968 + "Have to revert VM back to " + mNewVMNumber + " again."); 969 mPhone.setVoiceMailNumber( 970 mPhone.getVoiceMailAlphaTag().toString(), 971 mNewVMNumber, 972 Message.obtain(mRevertOptionComplete, EVENT_VOICEMAIL_CHANGED)); 973 } 974 975 if (mFwdChangesRequireRollback) { 976 Log.i(LOG_TAG, "Requested to rollback forwarding changes."); 977 978 final CallForwardInfo[] prevFwdSettings = prevSettings.getForwardingSettings(); 979 if (prevFwdSettings != null) { 980 Map<Integer, AsyncResult> results = mForwardingChangeResults; 981 resetForwardingChangeState(); 982 for (int i = 0; i < prevFwdSettings.length; i++) { 983 CallForwardInfo fi = prevFwdSettings[i]; 984 if (DBG) log("Reverting fwd #: " + i + ": " + fi.toString()); 985 // Only revert the settings for which the update succeeded. 986 AsyncResult result = results.get(fi.reason); 987 if (result != null && result.exception == null) { 988 mExpectedChangeResultReasons.add(fi.reason); 989 CallForwardInfoUtil.setCallForwardingOption(mPhone, fi, 990 mRevertOptionComplete.obtainMessage( 991 EVENT_FORWARDING_CHANGED, i, 0)); 992 } 993 } 994 } 995 } 996 } else { 997 if (DBG) log("No need to revert"); 998 onRevertDone(); 999 } 1000 } 1001 1002 1003 //********************************************************************************************* 1004 // Voicemail Handler Helpers 1005 //********************************************************************************************* 1006 1007 /** 1008 * Updates the look of the VM preference widgets based on current VM provider settings. 1009 * Note that the provider name is loaded fxrorm the found activity via loadLabel in 1010 * {@link VoicemailProviderListPreference#initVoiceMailProviders()} in order for it to be 1011 * localizable. 1012 */ 1013 private void updateVMPreferenceWidgets(String currentProviderSetting) { 1014 final String key = currentProviderSetting; 1015 final VoicemailProviderListPreference.VoicemailProvider provider = 1016 mVoicemailProviders.getVoicemailProvider(key); 1017 1018 /* This is the case when we are coming up on a freshly wiped phone and there is no 1019 persisted value for the list preference mVoicemailProviders. 1020 In this case we want to show the UI asking the user to select a voicemail provider as 1021 opposed to silently falling back to default one. */ 1022 if (provider == null) { 1023 if (DBG) log("updateVMPreferenceWidget: key: " + key + " -> null."); 1024 1025 mVoicemailProviders.setSummary(getString(R.string.sum_voicemail_choose_provider)); 1026 mVoicemailSettings.setEnabled(false); 1027 mVoicemailSettings.setIntent(null); 1028 } else { 1029 if (DBG) log("updateVMPreferenceWidget: key: " + key + " -> " + provider.toString()); 1030 1031 final String providerName = provider.name; 1032 mVoicemailProviders.setSummary(providerName); 1033 mVoicemailSettings.setEnabled(true); 1034 mVoicemailSettings.setIntent(provider.intent); 1035 } 1036 } 1037 1038 /** 1039 * Update the voicemail number from what we've recorded on the sim. 1040 */ 1041 private void updateVoiceNumberField() { 1042 if (DBG) log("updateVoiceNumberField()"); 1043 1044 mOldVmNumber = mPhone.getVoiceMailNumber(); 1045 if (TextUtils.isEmpty(mOldVmNumber)) { 1046 mSubMenuVoicemailSettings.setPhoneNumber(""); 1047 mSubMenuVoicemailSettings.setSummary(getString(R.string.voicemail_number_not_set)); 1048 } else { 1049 mSubMenuVoicemailSettings.setPhoneNumber(mOldVmNumber); 1050 mSubMenuVoicemailSettings.setSummary(BidiFormatter.getInstance().unicodeWrap( 1051 mOldVmNumber, TextDirectionHeuristics.LTR)); 1052 } 1053 } 1054 1055 private void handleSetVmOrFwdMessage() { 1056 if (DBG) log("handleSetVMMessage: set VM request complete"); 1057 1058 if (!isFwdChangeSuccess()) { 1059 handleVmOrFwdSetError(VoicemailDialogUtil.FWD_SET_RESPONSE_ERROR_DIALOG); 1060 } else if (!isVmChangeSuccess()) { 1061 handleVmOrFwdSetError(VoicemailDialogUtil.VM_RESPONSE_ERROR_DIALOG); 1062 } else { 1063 handleVmAndFwdSetSuccess(VoicemailDialogUtil.VM_CONFIRM_DIALOG); 1064 } 1065 } 1066 1067 /** 1068 * Called when Voicemail Provider or its forwarding settings failed. Rolls back partly made 1069 * changes to those settings and show "failure" dialog. 1070 * 1071 * @param dialogId ID of the dialog to show for the specific error case. Either 1072 * {@link #FWD_SET_RESPONSE_ERROR_DIALOG} or {@link #VM_RESPONSE_ERROR_DIALOG} 1073 */ 1074 private void handleVmOrFwdSetError(int dialogId) { 1075 if (mChangingVMorFwdDueToProviderChange) { 1076 mVMOrFwdSetError = dialogId; 1077 mChangingVMorFwdDueToProviderChange = false; 1078 switchToPreviousVoicemailProvider(); 1079 return; 1080 } 1081 mChangingVMorFwdDueToProviderChange = false; 1082 showDialogIfForeground(dialogId); 1083 updateVoiceNumberField(); 1084 } 1085 1086 /** 1087 * Called when Voicemail Provider and its forwarding settings were successfully finished. 1088 * This updates a bunch of variables and show "success" dialog. 1089 */ 1090 private void handleVmAndFwdSetSuccess(int dialogId) { 1091 if (DBG) log("handleVmAndFwdSetSuccess: key is " + mVoicemailProviders.getKey()); 1092 1093 mPreviousVMProviderKey = mVoicemailProviders.getKey(); 1094 mChangingVMorFwdDueToProviderChange = false; 1095 showDialogIfForeground(dialogId); 1096 updateVoiceNumberField(); 1097 } 1098 1099 private void onRevertDone() { 1100 if (DBG) log("onRevertDone: Changing provider key back to " + mPreviousVMProviderKey); 1101 1102 updateVMPreferenceWidgets(mPreviousVMProviderKey); 1103 updateVoiceNumberField(); 1104 if (mVMOrFwdSetError != 0) { 1105 showDialogIfForeground(mVMOrFwdSetError); 1106 mVMOrFwdSetError = 0; 1107 } 1108 } 1109 1110 1111 //********************************************************************************************* 1112 // Voicemail State Helpers 1113 //********************************************************************************************* 1114 1115 /** 1116 * Return true if there is a change result for every reason for which we expect a result. 1117 */ 1118 private boolean isForwardingCompleted() { 1119 if (mForwardingChangeResults == null) { 1120 return true; 1121 } 1122 1123 for (Integer reason : mExpectedChangeResultReasons) { 1124 if (mForwardingChangeResults.get(reason) == null) { 1125 return false; 1126 } 1127 } 1128 1129 return true; 1130 } 1131 1132 private boolean isFwdChangeSuccess() { 1133 if (mForwardingChangeResults == null) { 1134 return true; 1135 } 1136 1137 for (AsyncResult result : mForwardingChangeResults.values()) { 1138 Throwable exception = result.exception; 1139 if (exception != null) { 1140 String msg = exception.getMessage(); 1141 msg = (msg != null) ? msg : ""; 1142 Log.w(LOG_TAG, "Failed to change forwarding setting. Reason: " + msg); 1143 return false; 1144 } 1145 } 1146 return true; 1147 } 1148 1149 private boolean isVmChangeSuccess() { 1150 if (mVoicemailChangeResult.exception != null) { 1151 String msg = mVoicemailChangeResult.exception.getMessage(); 1152 msg = (msg != null) ? msg : ""; 1153 Log.w(LOG_TAG, "Failed to change voicemail. Reason: " + msg); 1154 return false; 1155 } 1156 return true; 1157 } 1158 1159 private static void log(String msg) { 1160 Log.d(LOG_TAG, msg); 1161 } 1162 } 1163