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