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.provider.ContactsContract.CommonDataKinds; 33 import android.provider.Settings; 34 import android.telecom.PhoneAccountHandle; 35 import android.telephony.CarrierConfigManager; 36 import android.telephony.TelephonyManager; 37 import android.text.BidiFormatter; 38 import android.text.TextDirectionHeuristics; 39 import android.text.TextUtils; 40 import android.util.Log; 41 import android.view.MenuItem; 42 import android.widget.ListAdapter; 43 import android.widget.Toast; 44 45 import com.android.internal.telephony.CallForwardInfo; 46 import com.android.internal.telephony.CommandsInterface; 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 onCreate(Bundle icicle)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 onResume()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 */ maybeHidePublicSettings()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 onPause()319 public void onPause() { 320 super.onPause(); 321 mForeground = false; 322 } 323 324 @Override onOptionsItemSelected(MenuItem item)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 onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference)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 onPreferenceChange(Preference preference, Object objValue)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 onGetDefaultNumber(EditPhoneNumberPreference preference)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 onActivityResult(int requestCode, int resultCode, Intent data)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 */ simulatePreferenceClick(Preference preference)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 */ getBooleanCarrierConfig(String key)568 private boolean getBooleanCarrierConfig(String key) { 569 PersistableBundle b = PhoneGlobals.getInstance() 570 .getCarrierConfigForSubId(mPhone.getSubId()); 571 572 if (b == null) { 573 b = PhoneGlobals.getInstance().getCarrierConfig(); 574 } 575 576 return b.getBoolean(key); 577 } 578 579 580 //********************************************************************************************* 581 // Activity Dialog Methods 582 //********************************************************************************************* 583 584 @Override onPrepareDialog(int id, Dialog dialog)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 onCreateDialog(int dialogId)592 protected Dialog onCreateDialog(int dialogId) { 593 return VoicemailDialogUtil.getDialog(this, dialogId); 594 } 595 596 @Override onDialogClosed(EditPhoneNumberPreference preference, int buttonClicked)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. showDialogIfForeground(int id)639 private void showDialogIfForeground(int id) { 640 if (mForeground) { 641 showDialog(id); 642 } 643 } 644 dismissDialogSafely(int id)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. onClick(DialogInterface dialog, int which)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 */ saveVoiceMailAndForwardingNumber( String key, VoicemailProviderSettings newSettings)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 CommandsInterface.SERVICE_CLASS_VOICE, 738 mGetOptionComplete.obtainMessage(EVENT_FORWARDING_GET_COMPLETED, i, 0)); 739 } 740 showDialogIfForeground(VoicemailDialogUtil.VM_FWD_READING_DIALOG); 741 } 742 } 743 744 private final Handler mGetOptionComplete = new Handler() { 745 @Override 746 public void handleMessage(Message msg) { 747 AsyncResult result = (AsyncResult) msg.obj; 748 switch (msg.what) { 749 case EVENT_FORWARDING_GET_COMPLETED: 750 handleForwardingSettingsReadResult(result, msg.arg1); 751 break; 752 } 753 } 754 }; 755 handleForwardingSettingsReadResult(AsyncResult ar, int idx)756 private void handleForwardingSettingsReadResult(AsyncResult ar, int idx) { 757 if (DBG) Log.d(LOG_TAG, "handleForwardingSettingsReadResult: " + idx); 758 759 Throwable error = null; 760 if (ar.exception != null) { 761 error = ar.exception; 762 if (DBG) Log.d(LOG_TAG, "FwdRead: ar.exception=" + error.getMessage()); 763 } 764 if (ar.userObj instanceof Throwable) { 765 error = (Throwable) ar.userObj; 766 if (DBG) Log.d(LOG_TAG, "FwdRead: userObj=" + error.getMessage()); 767 } 768 769 // We may have already gotten an error and decided to ignore the other results. 770 if (mForwardingReadResults == null) { 771 if (DBG) Log.d(LOG_TAG, "Ignoring fwd reading result: " + idx); 772 return; 773 } 774 775 // In case of error ignore other results, show an error dialog 776 if (error != null) { 777 if (DBG) Log.d(LOG_TAG, "Error discovered for fwd read : " + idx); 778 mForwardingReadResults = null; 779 dismissDialogSafely(VoicemailDialogUtil.VM_FWD_READING_DIALOG); 780 showDialogIfForeground(VoicemailDialogUtil.FWD_GET_RESPONSE_ERROR_DIALOG); 781 return; 782 } 783 784 // Get the forwarding info. 785 mForwardingReadResults[idx] = CallForwardInfoUtil.getCallForwardInfo( 786 (CallForwardInfo[]) ar.result, 787 VoicemailProviderSettings.FORWARDING_SETTINGS_REASONS[idx]); 788 789 // Check if we got all the results already 790 boolean done = true; 791 for (int i = 0; i < mForwardingReadResults.length; i++) { 792 if (mForwardingReadResults[i] == null) { 793 done = false; 794 break; 795 } 796 } 797 798 if (done) { 799 if (DBG) Log.d(LOG_TAG, "Done receiving fwd info"); 800 dismissDialogSafely(VoicemailDialogUtil.VM_FWD_READING_DIALOG); 801 802 if (mPreviousVMProviderKey.equals(VoicemailProviderListPreference.DEFAULT_KEY)) { 803 VoicemailProviderSettingsUtil.save(mPhone.getContext(), 804 VoicemailProviderListPreference.DEFAULT_KEY, 805 new VoicemailProviderSettings(mOldVmNumber, mForwardingReadResults)); 806 } 807 saveVoiceMailAndForwardingNumberStage2(); 808 } 809 } 810 resetForwardingChangeState()811 private void resetForwardingChangeState() { 812 mForwardingChangeResults = new HashMap<Integer, AsyncResult>(); 813 mExpectedChangeResultReasons = new HashSet<Integer>(); 814 } 815 816 // Called after we are done saving the previous forwarding settings if we needed. saveVoiceMailAndForwardingNumberStage2()817 private void saveVoiceMailAndForwardingNumberStage2() { 818 mForwardingChangeResults = null; 819 mVoicemailChangeResult = null; 820 821 resetForwardingChangeState(); 822 for (int i = 0; i < mNewFwdSettings.length; i++) { 823 CallForwardInfo fi = mNewFwdSettings[i]; 824 CallForwardInfo fiForReason = 825 CallForwardInfoUtil.infoForReason(mForwardingReadResults, fi.reason); 826 final boolean doUpdate = CallForwardInfoUtil.isUpdateRequired(fiForReason, fi); 827 828 if (doUpdate) { 829 if (DBG) log("Setting fwd #: " + i + ": " + fi.toString()); 830 mExpectedChangeResultReasons.add(i); 831 832 CallForwardInfoUtil.setCallForwardingOption(mPhone, fi, 833 mSetOptionComplete.obtainMessage( 834 EVENT_FORWARDING_CHANGED, fi.reason, 0)); 835 } 836 } 837 showDialogIfForeground(VoicemailDialogUtil.VM_FWD_SAVING_DIALOG); 838 } 839 840 841 /** 842 * Callback to handle option update completions 843 */ 844 private final Handler mSetOptionComplete = new Handler() { 845 @Override 846 public void handleMessage(Message msg) { 847 AsyncResult result = (AsyncResult) msg.obj; 848 boolean done = false; 849 switch (msg.what) { 850 case EVENT_VOICEMAIL_CHANGED: 851 mVoicemailChangeResult = result; 852 mVMChangeCompletedSuccessfully = isVmChangeSuccess(); 853 PhoneGlobals.getInstance().refreshMwiIndicator( 854 mSubscriptionInfoHelper.getSubId()); 855 done = true; 856 break; 857 case EVENT_FORWARDING_CHANGED: 858 mForwardingChangeResults.put(msg.arg1, result); 859 if (result.exception != null) { 860 Log.w(LOG_TAG, "Error in setting fwd# " + msg.arg1 + ": " + 861 result.exception.getMessage()); 862 } 863 if (isForwardingCompleted()) { 864 if (isFwdChangeSuccess()) { 865 if (DBG) log("Overall fwd changes completed ok, starting vm change"); 866 setVoicemailNumberWithCarrier(); 867 } else { 868 Log.w(LOG_TAG, "Overall fwd changes completed in failure. " + 869 "Check if we need to try rollback for some settings."); 870 mFwdChangesRequireRollback = false; 871 Iterator<Map.Entry<Integer,AsyncResult>> it = 872 mForwardingChangeResults.entrySet().iterator(); 873 while (it.hasNext()) { 874 Map.Entry<Integer,AsyncResult> entry = it.next(); 875 if (entry.getValue().exception == null) { 876 // If at least one succeeded we have to revert 877 Log.i(LOG_TAG, "Rollback will be required"); 878 mFwdChangesRequireRollback = true; 879 break; 880 } 881 } 882 if (!mFwdChangesRequireRollback) { 883 Log.i(LOG_TAG, "No rollback needed."); 884 } 885 done = true; 886 } 887 } 888 break; 889 default: 890 // TODO: should never reach this, may want to throw exception 891 } 892 893 if (done) { 894 if (DBG) log("All VM provider related changes done"); 895 if (mForwardingChangeResults != null) { 896 dismissDialogSafely(VoicemailDialogUtil.VM_FWD_SAVING_DIALOG); 897 } 898 handleSetVmOrFwdMessage(); 899 } 900 } 901 }; 902 903 /** 904 * Callback to handle option revert completions 905 */ 906 private final Handler mRevertOptionComplete = new Handler() { 907 @Override 908 public void handleMessage(Message msg) { 909 AsyncResult result = (AsyncResult) msg.obj; 910 switch (msg.what) { 911 case EVENT_VOICEMAIL_CHANGED: 912 if (DBG) log("VM revert complete msg"); 913 mVoicemailChangeResult = result; 914 break; 915 916 case EVENT_FORWARDING_CHANGED: 917 if (DBG) log("FWD revert complete msg "); 918 mForwardingChangeResults.put(msg.arg1, result); 919 if (result.exception != null) { 920 if (DBG) log("Error in reverting fwd# " + msg.arg1 + ": " + 921 result.exception.getMessage()); 922 } 923 break; 924 925 default: 926 // TODO: should never reach this, may want to throw exception 927 } 928 929 final boolean done = (!mVMChangeCompletedSuccessfully || mVoicemailChangeResult != null) 930 && (!mFwdChangesRequireRollback || isForwardingCompleted()); 931 if (done) { 932 if (DBG) log("All VM reverts done"); 933 dismissDialogSafely(VoicemailDialogUtil.VM_REVERTING_DIALOG); 934 onRevertDone(); 935 } 936 } 937 }; 938 setVoicemailNumberWithCarrier()939 private void setVoicemailNumberWithCarrier() { 940 if (DBG) log("save voicemail #: " + mNewVMNumber); 941 942 mVoicemailChangeResult = null; 943 mPhone.setVoiceMailNumber( 944 mPhone.getVoiceMailAlphaTag().toString(), 945 mNewVMNumber, 946 Message.obtain(mSetOptionComplete, EVENT_VOICEMAIL_CHANGED)); 947 } 948 switchToPreviousVoicemailProvider()949 private void switchToPreviousVoicemailProvider() { 950 if (DBG) log("switchToPreviousVoicemailProvider " + mPreviousVMProviderKey); 951 952 if (mPreviousVMProviderKey == null) { 953 return; 954 } 955 956 if (mVMChangeCompletedSuccessfully || mFwdChangesRequireRollback) { 957 showDialogIfForeground(VoicemailDialogUtil.VM_REVERTING_DIALOG); 958 final VoicemailProviderSettings prevSettings = 959 VoicemailProviderSettingsUtil.load(this, mPreviousVMProviderKey); 960 if (prevSettings == null) { 961 Log.e(LOG_TAG, "VoicemailProviderSettings for the key \"" 962 + mPreviousVMProviderKey + "\" is null but should be loaded."); 963 return; 964 } 965 966 if (mVMChangeCompletedSuccessfully) { 967 mNewVMNumber = prevSettings.getVoicemailNumber(); 968 Log.i(LOG_TAG, "VM change is already completed successfully." 969 + "Have to revert VM back to " + mNewVMNumber + " again."); 970 mPhone.setVoiceMailNumber( 971 mPhone.getVoiceMailAlphaTag().toString(), 972 mNewVMNumber, 973 Message.obtain(mRevertOptionComplete, EVENT_VOICEMAIL_CHANGED)); 974 } 975 976 if (mFwdChangesRequireRollback) { 977 Log.i(LOG_TAG, "Requested to rollback forwarding changes."); 978 979 final CallForwardInfo[] prevFwdSettings = prevSettings.getForwardingSettings(); 980 if (prevFwdSettings != null) { 981 Map<Integer, AsyncResult> results = mForwardingChangeResults; 982 resetForwardingChangeState(); 983 for (int i = 0; i < prevFwdSettings.length; i++) { 984 CallForwardInfo fi = prevFwdSettings[i]; 985 if (DBG) log("Reverting fwd #: " + i + ": " + fi.toString()); 986 // Only revert the settings for which the update succeeded. 987 AsyncResult result = results.get(fi.reason); 988 if (result != null && result.exception == null) { 989 mExpectedChangeResultReasons.add(fi.reason); 990 CallForwardInfoUtil.setCallForwardingOption(mPhone, fi, 991 mRevertOptionComplete.obtainMessage( 992 EVENT_FORWARDING_CHANGED, i, 0)); 993 } 994 } 995 } 996 } 997 } else { 998 if (DBG) log("No need to revert"); 999 onRevertDone(); 1000 } 1001 } 1002 1003 1004 //********************************************************************************************* 1005 // Voicemail Handler Helpers 1006 //********************************************************************************************* 1007 1008 /** 1009 * Updates the look of the VM preference widgets based on current VM provider settings. 1010 * Note that the provider name is loaded fxrorm the found activity via loadLabel in 1011 * {@link VoicemailProviderListPreference#initVoiceMailProviders()} in order for it to be 1012 * localizable. 1013 */ updateVMPreferenceWidgets(String currentProviderSetting)1014 private void updateVMPreferenceWidgets(String currentProviderSetting) { 1015 final String key = currentProviderSetting; 1016 final VoicemailProviderListPreference.VoicemailProvider provider = 1017 mVoicemailProviders.getVoicemailProvider(key); 1018 1019 /* This is the case when we are coming up on a freshly wiped phone and there is no 1020 persisted value for the list preference mVoicemailProviders. 1021 In this case we want to show the UI asking the user to select a voicemail provider as 1022 opposed to silently falling back to default one. */ 1023 if (provider == null) { 1024 if (DBG) log("updateVMPreferenceWidget: key: " + key + " -> null."); 1025 1026 mVoicemailProviders.setSummary(getString(R.string.sum_voicemail_choose_provider)); 1027 mVoicemailSettings.setEnabled(false); 1028 mVoicemailSettings.setIntent(null); 1029 } else { 1030 if (DBG) log("updateVMPreferenceWidget: key: " + key + " -> " + provider.toString()); 1031 1032 final String providerName = provider.name; 1033 mVoicemailProviders.setSummary(providerName); 1034 mVoicemailSettings.setEnabled(true); 1035 mVoicemailSettings.setIntent(provider.intent); 1036 } 1037 } 1038 1039 /** 1040 * Update the voicemail number from what we've recorded on the sim. 1041 */ updateVoiceNumberField()1042 private void updateVoiceNumberField() { 1043 if (DBG) log("updateVoiceNumberField()"); 1044 1045 mOldVmNumber = mPhone.getVoiceMailNumber(); 1046 if (TextUtils.isEmpty(mOldVmNumber)) { 1047 mSubMenuVoicemailSettings.setPhoneNumber(""); 1048 mSubMenuVoicemailSettings.setSummary(getString(R.string.voicemail_number_not_set)); 1049 } else { 1050 mSubMenuVoicemailSettings.setPhoneNumber(mOldVmNumber); 1051 mSubMenuVoicemailSettings.setSummary(BidiFormatter.getInstance().unicodeWrap( 1052 mOldVmNumber, TextDirectionHeuristics.LTR)); 1053 } 1054 } 1055 handleSetVmOrFwdMessage()1056 private void handleSetVmOrFwdMessage() { 1057 if (DBG) log("handleSetVMMessage: set VM request complete"); 1058 1059 if (!isFwdChangeSuccess()) { 1060 handleVmOrFwdSetError(VoicemailDialogUtil.FWD_SET_RESPONSE_ERROR_DIALOG); 1061 } else if (!isVmChangeSuccess()) { 1062 handleVmOrFwdSetError(VoicemailDialogUtil.VM_RESPONSE_ERROR_DIALOG); 1063 } else { 1064 handleVmAndFwdSetSuccess(VoicemailDialogUtil.VM_CONFIRM_DIALOG); 1065 } 1066 } 1067 1068 /** 1069 * Called when Voicemail Provider or its forwarding settings failed. Rolls back partly made 1070 * changes to those settings and show "failure" dialog. 1071 * 1072 * @param dialogId ID of the dialog to show for the specific error case. Either 1073 * {@link #FWD_SET_RESPONSE_ERROR_DIALOG} or {@link #VM_RESPONSE_ERROR_DIALOG} 1074 */ handleVmOrFwdSetError(int dialogId)1075 private void handleVmOrFwdSetError(int dialogId) { 1076 if (mChangingVMorFwdDueToProviderChange) { 1077 mVMOrFwdSetError = dialogId; 1078 mChangingVMorFwdDueToProviderChange = false; 1079 switchToPreviousVoicemailProvider(); 1080 return; 1081 } 1082 mChangingVMorFwdDueToProviderChange = false; 1083 showDialogIfForeground(dialogId); 1084 updateVoiceNumberField(); 1085 } 1086 1087 /** 1088 * Called when Voicemail Provider and its forwarding settings were successfully finished. 1089 * This updates a bunch of variables and show "success" dialog. 1090 */ handleVmAndFwdSetSuccess(int dialogId)1091 private void handleVmAndFwdSetSuccess(int dialogId) { 1092 if (DBG) log("handleVmAndFwdSetSuccess: key is " + mVoicemailProviders.getKey()); 1093 1094 mPreviousVMProviderKey = mVoicemailProviders.getKey(); 1095 mChangingVMorFwdDueToProviderChange = false; 1096 showDialogIfForeground(dialogId); 1097 updateVoiceNumberField(); 1098 } 1099 onRevertDone()1100 private void onRevertDone() { 1101 if (DBG) log("onRevertDone: Changing provider key back to " + mPreviousVMProviderKey); 1102 1103 updateVMPreferenceWidgets(mPreviousVMProviderKey); 1104 updateVoiceNumberField(); 1105 if (mVMOrFwdSetError != 0) { 1106 showDialogIfForeground(mVMOrFwdSetError); 1107 mVMOrFwdSetError = 0; 1108 } 1109 } 1110 1111 1112 //********************************************************************************************* 1113 // Voicemail State Helpers 1114 //********************************************************************************************* 1115 1116 /** 1117 * Return true if there is a change result for every reason for which we expect a result. 1118 */ isForwardingCompleted()1119 private boolean isForwardingCompleted() { 1120 if (mForwardingChangeResults == null) { 1121 return true; 1122 } 1123 1124 for (Integer reason : mExpectedChangeResultReasons) { 1125 if (mForwardingChangeResults.get(reason) == null) { 1126 return false; 1127 } 1128 } 1129 1130 return true; 1131 } 1132 isFwdChangeSuccess()1133 private boolean isFwdChangeSuccess() { 1134 if (mForwardingChangeResults == null) { 1135 return true; 1136 } 1137 1138 for (AsyncResult result : mForwardingChangeResults.values()) { 1139 Throwable exception = result.exception; 1140 if (exception != null) { 1141 String msg = exception.getMessage(); 1142 msg = (msg != null) ? msg : ""; 1143 Log.w(LOG_TAG, "Failed to change forwarding setting. Reason: " + msg); 1144 return false; 1145 } 1146 } 1147 return true; 1148 } 1149 isVmChangeSuccess()1150 private boolean isVmChangeSuccess() { 1151 if (mVoicemailChangeResult.exception != null) { 1152 String msg = mVoicemailChangeResult.exception.getMessage(); 1153 msg = (msg != null) ? msg : ""; 1154 Log.w(LOG_TAG, "Failed to change voicemail. Reason: " + msg); 1155 return false; 1156 } 1157 return true; 1158 } 1159 log(String msg)1160 private static void log(String msg) { 1161 Log.d(LOG_TAG, msg); 1162 } 1163 } 1164