blob: b207c7768c53ddad6ccd99b6a90abda18af5a8b3 [file] [log] [blame]
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.phone;
18
19import android.app.ActionBar;
20import android.app.Activity;
Evan Charlton1c696832014-04-15 14:24:23 -070021import android.app.ActivityOptions;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070022import android.app.AlertDialog;
23import android.app.Dialog;
24import android.app.ProgressDialog;
25import android.content.ContentResolver;
26import android.content.Context;
27import android.content.DialogInterface;
28import android.content.Intent;
29import android.content.SharedPreferences;
30import android.content.SharedPreferences.Editor;
31import android.content.pm.ActivityInfo;
32import android.content.pm.PackageManager;
33import android.content.pm.ResolveInfo;
34import android.database.Cursor;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070035import android.media.AudioManager;
36import android.media.RingtoneManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070037import android.os.AsyncResult;
38import android.os.Bundle;
39import android.os.Handler;
40import android.os.Message;
41import android.os.UserHandle;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070042import android.preference.CheckBoxPreference;
43import android.preference.ListPreference;
44import android.preference.Preference;
45import android.preference.PreferenceActivity;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070046import android.preference.PreferenceManager;
47import android.preference.PreferenceScreen;
48import android.provider.ContactsContract.CommonDataKinds;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070049import android.provider.Settings;
Tyler Gunn4d45d1c2014-09-12 22:17:53 -070050import android.telecom.PhoneAccountHandle;
51import android.telecom.TelecomManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070052import android.telephony.PhoneNumberUtils;
Andrew Lee93c345f2014-10-27 15:25:07 -070053import android.telephony.TelephonyManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070054import android.text.TextUtils;
55import android.util.Log;
56import android.view.MenuItem;
57import android.view.WindowManager;
58import android.widget.ListAdapter;
59
60import com.android.internal.telephony.CallForwardInfo;
61import com.android.internal.telephony.CommandsInterface;
62import com.android.internal.telephony.Phone;
63import com.android.internal.telephony.PhoneConstants;
Andrew Lee2170a972014-08-13 18:13:01 -070064import com.android.phone.common.util.SettingsUtil;
Andrew Leedb2fe562014-09-03 15:40:43 -070065import com.android.phone.settings.AccountSelectionPreference;
Andrew Leeb490d732014-10-27 15:00:41 -070066import com.android.phone.settings.VoicemailProviderSettings;
Sailesh Nepal788959e2014-07-08 23:36:40 -070067import com.android.services.telephony.sip.SipUtil;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070068
Andrew Lee2170a972014-08-13 18:13:01 -070069import java.lang.String;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070070import java.util.Collection;
71import java.util.HashMap;
72import java.util.HashSet;
73import java.util.Iterator;
74import java.util.List;
75import java.util.Map;
76
77/**
78 * Top level "Call settings" UI; see res/xml/call_feature_setting.xml
79 *
Andrew Leece8ae2a2014-09-10 10:41:48 -070080 * This preference screen is the root of the "Call settings" hierarchy available from the Phone
81 * app; the settings here let you control various features related to phone calls (including
82 * voicemail settings, the "Respond via SMS" feature, and others.) It's used only on
83 * voice-capable phone devices.
Santos Cordon7d4ddf62013-07-10 11:58:08 -070084 *
85 * Note that this activity is part of the package com.android.phone, even
86 * though you reach it from the "Phone" app (i.e. DialtactsActivity) which
87 * is from the package com.android.contacts.
88 *
89 * For the "Mobile network settings" screen under the main Settings app,
90 * See {@link MobileNetworkSettings}.
91 *
Andrew Leece8ae2a2014-09-10 10:41:48 -070092 * TODO: Settings should be split into PreferenceFragments where possible (ie. voicemail).
Andrew Lee2170a972014-08-13 18:13:01 -070093 *
Santos Cordon7d4ddf62013-07-10 11:58:08 -070094 * @see com.android.phone.MobileNetworkSettings
95 */
96public class CallFeaturesSetting extends PreferenceActivity
97 implements DialogInterface.OnClickListener,
Andrew Lee2170a972014-08-13 18:13:01 -070098 Preference.OnPreferenceChangeListener,
Andrew Lee2170a972014-08-13 18:13:01 -070099 EditPhoneNumberPreference.OnDialogClosedListener,
Andrew Leece8ae2a2014-09-10 10:41:48 -0700100 EditPhoneNumberPreference.GetDefaultNumberListener {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700101 private static final String LOG_TAG = "CallFeaturesSetting";
102 private static final boolean DBG = (PhoneGlobals.DBG_LEVEL >= 2);
Andrew Lee77527ac2014-10-21 16:57:39 -0700103 // STOPSHIP if true. Flag to override behavior default behavior to hide VT setting.
104 private static final boolean ENABLE_VT_FLAG = false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700105
106 /**
107 * Intent action to bring up Voicemail Provider settings.
108 *
109 * @see #IGNORE_PROVIDER_EXTRA
110 */
111 public static final String ACTION_ADD_VOICEMAIL =
112 "com.android.phone.CallFeaturesSetting.ADD_VOICEMAIL";
113 // intent action sent by this activity to a voice mail provider
114 // to trigger its configuration UI
115 public static final String ACTION_CONFIGURE_VOICEMAIL =
116 "com.android.phone.CallFeaturesSetting.CONFIGURE_VOICEMAIL";
Andrew Leee3c15212014-10-28 13:12:55 -0700117 // Extra on intent to Call Settings containing the id of the subscription to modify.
118 public static final String SUB_ID_EXTRA =
119 "com.android.phone.CallFeaturesSetting.SubscriptionId";
120 // Extra on intent to Call Settings containing the label of the subscription to modify.
121 public static final String SUB_LABEL_EXTRA =
122 "com.android.phone.CallFeaturesSetting.SubscriptionLabel";
123
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700124 // Extra put in the return from VM provider config containing voicemail number to set
125 public static final String VM_NUMBER_EXTRA = "com.android.phone.VoicemailNumber";
126 // Extra put in the return from VM provider config containing call forwarding number to set
127 public static final String FWD_NUMBER_EXTRA = "com.android.phone.ForwardingNumber";
128 // Extra put in the return from VM provider config containing call forwarding number to set
129 public static final String FWD_NUMBER_TIME_EXTRA = "com.android.phone.ForwardingNumberTime";
130 // If the VM provider returns non null value in this extra we will force the user to
131 // choose another VM provider
132 public static final String SIGNOUT_EXTRA = "com.android.phone.Signout";
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700133
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700134 // Suffix appended to provider key for storing vm number
135 public static final String VM_NUMBER_TAG = "#VMNumber";
136 // Suffix appended to provider key for storing forwarding settings
137 public static final String FWD_SETTINGS_TAG = "#FWDSettings";
138 // Suffix appended to forward settings key for storing length of settings array
139 public static final String FWD_SETTINGS_LENGTH_TAG = "#Length";
140 // Suffix appended to forward settings key for storing an individual setting
141 public static final String FWD_SETTING_TAG = "#Setting";
142 // Suffixes appended to forward setting key for storing an individual setting properties
143 public static final String FWD_SETTING_STATUS = "#Status";
144 public static final String FWD_SETTING_REASON = "#Reason";
145 public static final String FWD_SETTING_NUMBER = "#Number";
146 public static final String FWD_SETTING_TIME = "#Time";
147
148 // Key identifying the default vocie mail provider
149 public static final String DEFAULT_VM_PROVIDER_KEY = "";
150
151 /**
152 * String Extra put into ACTION_ADD_VOICEMAIL call to indicate which provider should be hidden
153 * in the list of providers presented to the user. This allows a provider which is being
154 * disabled (e.g. GV user logging out) to force the user to pick some other provider.
155 */
156 public static final String IGNORE_PROVIDER_EXTRA = "com.android.phone.ProviderToIgnore";
157
158 // string constants
159 private static final String NUM_PROJECTION[] = {CommonDataKinds.Phone.NUMBER};
160
161 // String keys for preference lookup
162 // TODO: Naming these "BUTTON_*" is confusing since they're not actually buttons(!)
Andrew Lee97708a42014-09-25 12:39:07 -0700163 private static final String VOICEMAIL_SETTING_SCREEN_PREF_KEY = "button_voicemail_category_key";
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700164 private static final String BUTTON_VOICEMAIL_KEY = "button_voicemail_key";
165 private static final String BUTTON_VOICEMAIL_PROVIDER_KEY = "button_voicemail_provider_key";
166 private static final String BUTTON_VOICEMAIL_SETTING_KEY = "button_voicemail_setting_key";
167 // New preference key for voicemail notification vibration
168 /* package */ static final String BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY =
169 "button_voicemail_notification_vibrate_key";
170 // Old preference key for voicemail notification vibration. Used for migration to the new
171 // preference key only.
172 /* package */ static final String BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_WHEN_KEY =
173 "button_voicemail_notification_vibrate_when_key";
174 /* package */ static final String BUTTON_VOICEMAIL_NOTIFICATION_RINGTONE_KEY =
175 "button_voicemail_notification_ringtone_key";
176 private static final String BUTTON_FDN_KEY = "button_fdn_key";
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700177
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700178 private static final String BUTTON_DTMF_KEY = "button_dtmf_settings";
179 private static final String BUTTON_RETRY_KEY = "button_auto_retry_key";
180 private static final String BUTTON_TTY_KEY = "button_tty_mode_key";
181 private static final String BUTTON_HAC_KEY = "button_hac_key";
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700182
183 private static final String BUTTON_GSM_UMTS_OPTIONS = "button_gsm_more_expand_key";
184 private static final String BUTTON_CDMA_OPTIONS = "button_cdma_more_expand_key";
185
186 private static final String VM_NUMBERS_SHARED_PREFERENCES_NAME = "vm_numbers";
187
Andrew Leedb2fe562014-09-03 15:40:43 -0700188 private static final String DEFAULT_OUTGOING_ACCOUNT_KEY = "default_outgoing_account";
Andrew Leece8ae2a2014-09-10 10:41:48 -0700189 private static final String PHONE_ACCOUNT_SETTINGS_KEY =
190 "phone_account_settings_preference_screen";
Andrew Leedb2fe562014-09-03 15:40:43 -0700191
Andrew Leedf14ead2014-10-17 14:22:52 -0700192 private static final String ENABLE_VIDEO_CALLING_KEY = "button_enable_video_calling";
193
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700194 private Intent mContactListIntent;
195
196 /** Event for Async voicemail change call */
197 private static final int EVENT_VOICEMAIL_CHANGED = 500;
198 private static final int EVENT_FORWARDING_CHANGED = 501;
199 private static final int EVENT_FORWARDING_GET_COMPLETED = 502;
200
Andrew Lee2170a972014-08-13 18:13:01 -0700201 private static final int MSG_UPDATE_VOICEMAIL_RINGTONE_SUMMARY = 1;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700202
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700203 public static final String HAC_KEY = "HACSetting";
204 public static final String HAC_VAL_ON = "ON";
205 public static final String HAC_VAL_OFF = "OFF";
206
207 /** Handle to voicemail pref */
208 private static final int VOICEMAIL_PREF_ID = 1;
209 private static final int VOICEMAIL_PROVIDER_CFG_ID = 2;
210
211 private Phone mPhone;
212
213 private AudioManager mAudioManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700214
215 private static final int VM_NOCHANGE_ERROR = 400;
216 private static final int VM_RESPONSE_ERROR = 500;
217 private static final int FW_SET_RESPONSE_ERROR = 501;
218 private static final int FW_GET_RESPONSE_ERROR = 502;
219
220
221 // dialog identifiers for voicemail
222 private static final int VOICEMAIL_DIALOG_CONFIRM = 600;
223 private static final int VOICEMAIL_FWD_SAVING_DIALOG = 601;
224 private static final int VOICEMAIL_FWD_READING_DIALOG = 602;
225 private static final int VOICEMAIL_REVERTING_DIALOG = 603;
226
227 // status message sent back from handlers
228 private static final int MSG_OK = 100;
229
230 // special statuses for voicemail controls.
231 private static final int MSG_VM_EXCEPTION = 400;
232 private static final int MSG_FW_SET_EXCEPTION = 401;
233 private static final int MSG_FW_GET_EXCEPTION = 402;
234 private static final int MSG_VM_OK = 600;
235 private static final int MSG_VM_NOCHANGE = 700;
236
237 // voicemail notification vibration string constants
238 private static final String VOICEMAIL_VIBRATION_ALWAYS = "always";
239 private static final String VOICEMAIL_VIBRATION_NEVER = "never";
240
241 private EditPhoneNumberPreference mSubMenuVoicemailSettings;
242
Andrew Lee2170a972014-08-13 18:13:01 -0700243 private Runnable mVoicemailRingtoneLookupRunnable;
244 private final Handler mVoicemailRingtoneLookupComplete = new Handler() {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700245 @Override
246 public void handleMessage(Message msg) {
247 switch (msg.what) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700248 case MSG_UPDATE_VOICEMAIL_RINGTONE_SUMMARY:
249 mVoicemailNotificationRingtone.setSummary((CharSequence) msg.obj);
250 break;
251 }
252 }
253 };
254
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700255 /** Whether dialpad plays DTMF tone or not. */
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700256 private CheckBoxPreference mButtonAutoRetry;
257 private CheckBoxPreference mButtonHAC;
258 private ListPreference mButtonDTMF;
259 private ListPreference mButtonTTY;
Andrew Leece8ae2a2014-09-10 10:41:48 -0700260 private Preference mPhoneAccountSettingsPreference;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700261 private ListPreference mVoicemailProviders;
Andrew Lee97708a42014-09-25 12:39:07 -0700262 private PreferenceScreen mVoicemailSettingsScreen;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700263 private PreferenceScreen mVoicemailSettings;
264 private Preference mVoicemailNotificationRingtone;
265 private CheckBoxPreference mVoicemailNotificationVibrate;
Andrew Leedb2fe562014-09-03 15:40:43 -0700266 private AccountSelectionPreference mDefaultOutgoingAccount;
Andrew Leedf14ead2014-10-17 14:22:52 -0700267 private CheckBoxPreference mEnableVideoCalling;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700268
269 private class VoiceMailProvider {
270 public VoiceMailProvider(String name, Intent intent) {
271 this.name = name;
272 this.intent = intent;
273 }
274 public String name;
275 public Intent intent;
276 }
277
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700278 private SharedPreferences mPerProviderSavedVMNumbers;
279
280 /**
281 * Results of reading forwarding settings
282 */
283 private CallForwardInfo[] mForwardingReadResults = null;
284
285 /**
286 * Result of forwarding number change.
287 * Keys are reasons (eg. unconditional forwarding).
288 */
289 private Map<Integer, AsyncResult> mForwardingChangeResults = null;
290
291 /**
292 * Expected CF read result types.
293 * This set keeps track of the CF types for which we've issued change
294 * commands so we can tell when we've received all of the responses.
295 */
296 private Collection<Integer> mExpectedChangeResultReasons = null;
297
298 /**
299 * Result of vm number change
300 */
301 private AsyncResult mVoicemailChangeResult = null;
302
303 /**
304 * Previous VM provider setting so we can return to it in case of failure.
305 */
306 private String mPreviousVMProviderKey = null;
307
308 /**
309 * Id of the dialog being currently shown.
310 */
311 private int mCurrentDialogId = 0;
312
313 /**
314 * Flag indicating that we are invoking settings for the voicemail provider programmatically
315 * due to vm provider change.
316 */
317 private boolean mVMProviderSettingsForced = false;
318
319 /**
320 * Flag indicating that we are making changes to vm or fwd numbers
321 * due to vm provider change.
322 */
323 private boolean mChangingVMorFwdDueToProviderChange = false;
324
325 /**
326 * True if we are in the process of vm & fwd number change and vm has already been changed.
327 * This is used to decide what to do in case of rollback.
328 */
329 private boolean mVMChangeCompletedSuccessfully = false;
330
331 /**
332 * True if we had full or partial failure setting forwarding numbers and so need to roll them
333 * back.
334 */
335 private boolean mFwdChangesRequireRollback = false;
336
337 /**
338 * Id of error msg to display to user once we are done reverting the VM provider to the previous
339 * one.
340 */
341 private int mVMOrFwdSetError = 0;
342
343 /**
344 * Data about discovered voice mail settings providers.
345 * Is populated by querying which activities can handle ACTION_CONFIGURE_VOICEMAIL.
346 * They key in this map is package name + activity name.
347 * We always add an entry for the default provider with a key of empty
348 * string and intent value of null.
349 * @see #initVoiceMailProviders()
350 */
351 private final Map<String, VoiceMailProvider> mVMProvidersData =
352 new HashMap<String, VoiceMailProvider>();
353
354 /** string to hold old voicemail number as it is being updated. */
355 private String mOldVmNumber;
356
357 // New call forwarding settings and vm number we will be setting
358 // Need to save these since before we get to saving we need to asynchronously
359 // query the existing forwarding settings.
360 private CallForwardInfo[] mNewFwdSettings;
361 private String mNewVMNumber;
362
363 private boolean mForeground;
364
365 @Override
366 public void onPause() {
367 super.onPause();
368 mForeground = false;
369 }
370
371 /**
372 * We have to pull current settings from the network for all kinds of
373 * voicemail providers so we can tell whether we have to update them,
374 * so use this bit to keep track of whether we're reading settings for the
375 * default provider and should therefore save them out when done.
376 */
377 private boolean mReadingSettingsForDefaultProvider = false;
378
Tyler Gunnbaee2952014-09-10 16:01:02 -0700379 /**
380 * Used to indicate that the voicemail preference should be shown.
381 */
382 private boolean mShowVoicemailPreference = false;
383
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700384 /*
385 * Click Listeners, handle click based on objects attached to UI.
386 */
387
388 // Click listener for all toggle events
389 @Override
390 public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
391 if (preference == mSubMenuVoicemailSettings) {
392 return true;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700393 } else if (preference == mButtonDTMF) {
394 return true;
395 } else if (preference == mButtonTTY) {
396 return true;
397 } else if (preference == mButtonAutoRetry) {
398 android.provider.Settings.Global.putInt(mPhone.getContext().getContentResolver(),
399 android.provider.Settings.Global.CALL_AUTO_RETRY,
400 mButtonAutoRetry.isChecked() ? 1 : 0);
401 return true;
402 } else if (preference == mButtonHAC) {
403 int hac = mButtonHAC.isChecked() ? 1 : 0;
404 // Update HAC value in Settings database
405 Settings.System.putInt(mPhone.getContext().getContentResolver(),
406 Settings.System.HEARING_AID, hac);
407
408 // Update HAC Value in AudioManager
409 mAudioManager.setParameter(HAC_KEY, hac != 0 ? HAC_VAL_ON : HAC_VAL_OFF);
410 return true;
411 } else if (preference == mVoicemailSettings) {
Yorke Leea0f63bf2014-10-09 18:27:20 -0700412 final Dialog dialog = mVoicemailSettings.getDialog();
413 if (dialog != null) {
414 dialog.getActionBar().setDisplayHomeAsUpEnabled(false);
415 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700416 if (DBG) log("onPreferenceTreeClick: Voicemail Settings Preference is clicked.");
417 if (preference.getIntent() != null) {
418 if (DBG) {
419 log("onPreferenceTreeClick: Invoking cfg intent "
420 + preference.getIntent().getPackage());
421 }
422
423 // onActivityResult() will be responsible for resetting some of variables.
424 this.startActivityForResult(preference.getIntent(), VOICEMAIL_PROVIDER_CFG_ID);
425 return true;
426 } else {
427 if (DBG) {
428 log("onPreferenceTreeClick:"
429 + " No Intent is available. Use default behavior defined in xml.");
430 }
431
432 // There's no onActivityResult(), so we need to take care of some of variables
433 // which should be reset here.
434 mPreviousVMProviderKey = DEFAULT_VM_PROVIDER_KEY;
435 mVMProviderSettingsForced = false;
436
437 // This should let the preference use default behavior in the xml.
438 return false;
439 }
Andrew Lee97708a42014-09-25 12:39:07 -0700440 } else if (preference == mVoicemailSettingsScreen) {
Yorke Leea0f63bf2014-10-09 18:27:20 -0700441 final Dialog dialog = mVoicemailSettingsScreen.getDialog();
442 if (dialog != null) {
443 dialog.getActionBar().setDisplayHomeAsUpEnabled(false);
444 }
Andrew Lee97708a42014-09-25 12:39:07 -0700445 return false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700446 }
447 return false;
448 }
449
450 /**
451 * Implemented to support onPreferenceChangeListener to look for preference
452 * changes.
453 *
454 * @param preference is the preference to be changed
455 * @param objValue should be the value of the selection, NOT its localized
456 * display value.
457 */
458 @Override
459 public boolean onPreferenceChange(Preference preference, Object objValue) {
460 if (DBG) {
Andrew Leedf14ead2014-10-17 14:22:52 -0700461 log("onPreferenceChange(). preference: \"" + preference + "\""
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700462 + ", value: \"" + objValue + "\"");
463 }
Andrew Lee2170a972014-08-13 18:13:01 -0700464
465 if (preference == mButtonDTMF) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700466 int index = mButtonDTMF.findIndexOfValue((String) objValue);
467 Settings.System.putInt(mPhone.getContext().getContentResolver(),
468 Settings.System.DTMF_TONE_TYPE_WHEN_DIALING, index);
469 } else if (preference == mButtonTTY) {
470 handleTTYChange(preference, objValue);
471 } else if (preference == mVoicemailProviders) {
472 final String newProviderKey = (String) objValue;
473 if (DBG) {
474 log("Voicemail Provider changes from \"" + mPreviousVMProviderKey
475 + "\" to \"" + newProviderKey + "\".");
476 }
477 // If previous provider key and the new one is same, we don't need to handle it.
478 if (mPreviousVMProviderKey.equals(newProviderKey)) {
479 if (DBG) log("No change is made toward VM provider setting.");
480 return true;
481 }
482 updateVMPreferenceWidgets(newProviderKey);
483
Andrew Leeb490d732014-10-27 15:00:41 -0700484 final VoicemailProviderSettings newProviderSettings =
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700485 loadSettingsForVoiceMailProvider(newProviderKey);
486
487 // If the user switches to a voice mail provider and we have a
488 // numbers stored for it we will automatically change the
489 // phone's
490 // voice mail and forwarding number to the stored ones.
491 // Otherwise we will bring up provider's configuration UI.
492
493 if (newProviderSettings == null) {
494 // Force the user into a configuration of the chosen provider
495 Log.w(LOG_TAG, "Saved preferences not found - invoking config");
496 mVMProviderSettingsForced = true;
497 simulatePreferenceClick(mVoicemailSettings);
498 } else {
499 if (DBG) log("Saved preferences found - switching to them");
500 // Set this flag so if we get a failure we revert to previous provider
501 mChangingVMorFwdDueToProviderChange = true;
502 saveVoiceMailAndForwardingNumber(newProviderKey, newProviderSettings);
503 }
Andrew Leedf14ead2014-10-17 14:22:52 -0700504 } else if (preference == mEnableVideoCalling) {
505 PhoneGlobals.getInstance().phoneMgr.enableVideoCalling((boolean) objValue);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700506 }
507 // always let the preference setting proceed.
508 return true;
509 }
510
511 @Override
512 public void onDialogClosed(EditPhoneNumberPreference preference, int buttonClicked) {
513 if (DBG) log("onPreferenceClick: request preference click on dialog close: " +
514 buttonClicked);
515 if (buttonClicked == DialogInterface.BUTTON_NEGATIVE) {
516 return;
517 }
518
519 if (preference == mSubMenuVoicemailSettings) {
520 handleVMBtnClickRequest();
521 }
522 }
523
524 /**
525 * Implemented for EditPhoneNumberPreference.GetDefaultNumberListener.
526 * This method set the default values for the various
527 * EditPhoneNumberPreference dialogs.
528 */
529 @Override
530 public String onGetDefaultNumber(EditPhoneNumberPreference preference) {
531 if (preference == mSubMenuVoicemailSettings) {
532 // update the voicemail number field, which takes care of the
533 // mSubMenuVoicemailSettings itself, so we should return null.
534 if (DBG) log("updating default for voicemail dialog");
535 updateVoiceNumberField();
536 return null;
537 }
538
539 String vmDisplay = mPhone.getVoiceMailNumber();
540 if (TextUtils.isEmpty(vmDisplay)) {
541 // if there is no voicemail number, we just return null to
542 // indicate no contribution.
543 return null;
544 }
545
546 // Return the voicemail number prepended with "VM: "
547 if (DBG) log("updating default for call forwarding dialogs");
548 return getString(R.string.voicemail_abbreviated) + " " + vmDisplay;
549 }
550
551
552 // override the startsubactivity call to make changes in state consistent.
553 @Override
554 public void startActivityForResult(Intent intent, int requestCode) {
555 if (requestCode == -1) {
556 // this is an intent requested from the preference framework.
557 super.startActivityForResult(intent, requestCode);
558 return;
559 }
560
561 if (DBG) log("startSubActivity: starting requested subactivity");
562 super.startActivityForResult(intent, requestCode);
563 }
564
565 private void switchToPreviousVoicemailProvider() {
566 if (DBG) log("switchToPreviousVoicemailProvider " + mPreviousVMProviderKey);
567 if (mPreviousVMProviderKey != null) {
568 if (mVMChangeCompletedSuccessfully || mFwdChangesRequireRollback) {
569 // we have to revert with carrier
570 if (DBG) {
571 log("Needs to rollback."
572 + " mVMChangeCompletedSuccessfully=" + mVMChangeCompletedSuccessfully
573 + ", mFwdChangesRequireRollback=" + mFwdChangesRequireRollback);
574 }
575
576 showDialogIfForeground(VOICEMAIL_REVERTING_DIALOG);
Andrew Leeb490d732014-10-27 15:00:41 -0700577 final VoicemailProviderSettings prevSettings =
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700578 loadSettingsForVoiceMailProvider(mPreviousVMProviderKey);
579 if (prevSettings == null) {
580 // prevSettings never becomes null since it should be already loaded!
Andrew Leeb490d732014-10-27 15:00:41 -0700581 Log.e(LOG_TAG, "VoicemailProviderSettings for the key \""
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700582 + mPreviousVMProviderKey + "\" becomes null, which is unexpected.");
583 if (DBG) {
584 Log.e(LOG_TAG,
585 "mVMChangeCompletedSuccessfully: " + mVMChangeCompletedSuccessfully
586 + ", mFwdChangesRequireRollback: " + mFwdChangesRequireRollback);
587 }
588 }
589 if (mVMChangeCompletedSuccessfully) {
Andrew Leeb490d732014-10-27 15:00:41 -0700590 mNewVMNumber = prevSettings.getVoicemailNumber();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700591 Log.i(LOG_TAG, "VM change is already completed successfully."
592 + "Have to revert VM back to " + mNewVMNumber + " again.");
593 mPhone.setVoiceMailNumber(
594 mPhone.getVoiceMailAlphaTag().toString(),
595 mNewVMNumber,
596 Message.obtain(mRevertOptionComplete, EVENT_VOICEMAIL_CHANGED));
597 }
598 if (mFwdChangesRequireRollback) {
599 Log.i(LOG_TAG, "Requested to rollback Fwd changes.");
Andrew Leeb490d732014-10-27 15:00:41 -0700600 final CallForwardInfo[] prevFwdSettings = prevSettings.getForwardingSettings();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700601 if (prevFwdSettings != null) {
602 Map<Integer, AsyncResult> results =
603 mForwardingChangeResults;
604 resetForwardingChangeState();
605 for (int i = 0; i < prevFwdSettings.length; i++) {
606 CallForwardInfo fi = prevFwdSettings[i];
607 if (DBG) log("Reverting fwd #: " + i + ": " + fi.toString());
608 // Only revert the settings for which the update
609 // succeeded
610 AsyncResult result = results.get(fi.reason);
611 if (result != null && result.exception == null) {
612 mExpectedChangeResultReasons.add(fi.reason);
613 mPhone.setCallForwardingOption(
614 (fi.status == 1 ?
615 CommandsInterface.CF_ACTION_REGISTRATION :
616 CommandsInterface.CF_ACTION_DISABLE),
617 fi.reason,
618 fi.number,
619 fi.timeSeconds,
620 mRevertOptionComplete.obtainMessage(
621 EVENT_FORWARDING_CHANGED, i, 0));
622 }
623 }
624 }
625 }
626 } else {
627 if (DBG) log("No need to revert");
628 onRevertDone();
629 }
630 }
631 }
632
633 private void onRevertDone() {
634 if (DBG) log("Flipping provider key back to " + mPreviousVMProviderKey);
635 mVoicemailProviders.setValue(mPreviousVMProviderKey);
636 updateVMPreferenceWidgets(mPreviousVMProviderKey);
637 updateVoiceNumberField();
638 if (mVMOrFwdSetError != 0) {
639 showVMDialog(mVMOrFwdSetError);
640 mVMOrFwdSetError = 0;
641 }
642 }
643
644 @Override
645 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
646 if (DBG) {
647 log("onActivityResult: requestCode: " + requestCode
648 + ", resultCode: " + resultCode
649 + ", data: " + data);
650 }
651 // there are cases where the contact picker may end up sending us more than one
652 // request. We want to ignore the request if we're not in the correct state.
653 if (requestCode == VOICEMAIL_PROVIDER_CFG_ID) {
654 boolean failure = false;
655
656 // No matter how the processing of result goes lets clear the flag
657 if (DBG) log("mVMProviderSettingsForced: " + mVMProviderSettingsForced);
658 final boolean isVMProviderSettingsForced = mVMProviderSettingsForced;
659 mVMProviderSettingsForced = false;
660
661 String vmNum = null;
662 if (resultCode != RESULT_OK) {
663 if (DBG) log("onActivityResult: vm provider cfg result not OK.");
664 failure = true;
665 } else {
666 if (data == null) {
667 if (DBG) log("onActivityResult: vm provider cfg result has no data");
668 failure = true;
669 } else {
670 if (data.getBooleanExtra(SIGNOUT_EXTRA, false)) {
671 if (DBG) log("Provider requested signout");
672 if (isVMProviderSettingsForced) {
673 if (DBG) log("Going back to previous provider on signout");
674 switchToPreviousVoicemailProvider();
675 } else {
676 final String victim = getCurrentVoicemailProviderKey();
677 if (DBG) log("Relaunching activity and ignoring " + victim);
678 Intent i = new Intent(ACTION_ADD_VOICEMAIL);
679 i.putExtra(IGNORE_PROVIDER_EXTRA, victim);
680 i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
681 this.startActivity(i);
682 }
683 return;
684 }
685 vmNum = data.getStringExtra(VM_NUMBER_EXTRA);
686 if (vmNum == null || vmNum.length() == 0) {
687 if (DBG) log("onActivityResult: vm provider cfg result has no vmnum");
688 failure = true;
689 }
690 }
691 }
692 if (failure) {
693 if (DBG) log("Failure in return from voicemail provider");
694 if (isVMProviderSettingsForced) {
695 switchToPreviousVoicemailProvider();
696 } else {
697 if (DBG) log("Not switching back the provider since this is not forced config");
698 }
699 return;
700 }
701 mChangingVMorFwdDueToProviderChange = isVMProviderSettingsForced;
702 final String fwdNum = data.getStringExtra(FWD_NUMBER_EXTRA);
703
Santos Cordonda120f42014-08-06 04:44:34 -0700704 // TODO: It would be nice to load the current network setting for this and
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700705 // send it to the provider when it's config is invoked so it can use this as default
706 final int fwdNumTime = data.getIntExtra(FWD_NUMBER_TIME_EXTRA, 20);
707
708 if (DBG) log("onActivityResult: vm provider cfg result " +
709 (fwdNum != null ? "has" : " does not have") + " forwarding number");
710 saveVoiceMailAndForwardingNumber(getCurrentVoicemailProviderKey(),
Andrew Leeb490d732014-10-27 15:00:41 -0700711 new VoicemailProviderSettings(vmNum, fwdNum, fwdNumTime));
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700712 return;
713 }
714
715 if (requestCode == VOICEMAIL_PREF_ID) {
716 if (resultCode != RESULT_OK) {
717 if (DBG) log("onActivityResult: contact picker result not OK.");
718 return;
719 }
720
721 Cursor cursor = null;
722 try {
723 cursor = getContentResolver().query(data.getData(),
724 NUM_PROJECTION, null, null, null);
725 if ((cursor == null) || (!cursor.moveToFirst())) {
726 if (DBG) log("onActivityResult: bad contact data, no results found.");
727 return;
728 }
729 mSubMenuVoicemailSettings.onPickActivityResult(cursor.getString(0));
730 return;
731 } finally {
732 if (cursor != null) {
733 cursor.close();
734 }
735 }
736 }
737
738 super.onActivityResult(requestCode, resultCode, data);
739 }
740
741 // Voicemail button logic
742 private void handleVMBtnClickRequest() {
743 // normally called on the dialog close.
744
745 // Since we're stripping the formatting out on the getPhoneNumber()
746 // call now, we won't need to do so here anymore.
747
748 saveVoiceMailAndForwardingNumber(
749 getCurrentVoicemailProviderKey(),
Andrew Leeb490d732014-10-27 15:00:41 -0700750 new VoicemailProviderSettings(mSubMenuVoicemailSettings.getPhoneNumber(),
751 VoicemailProviderSettings.NO_FORWARDING)
Tyler Gunn4d45d1c2014-09-12 22:17:53 -0700752 );
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700753 }
754
755
756 /**
757 * Wrapper around showDialog() that will silently do nothing if we're
758 * not in the foreground.
759 *
760 * This is useful here because most of the dialogs we display from
761 * this class are triggered by asynchronous events (like
762 * success/failure messages from the telephony layer) and it's
763 * possible for those events to come in even after the user has gone
764 * to a different screen.
765 */
766 // TODO: this is too brittle: it's still easy to accidentally add new
767 // code here that calls showDialog() directly (which will result in a
768 // WindowManager$BadTokenException if called after the activity has
769 // been stopped.)
770 //
771 // It would be cleaner to do the "if (mForeground)" check in one
772 // central place, maybe by using a single Handler for all asynchronous
773 // events (and have *that* discard events if we're not in the
774 // foreground.)
775 //
776 // Unfortunately it's not that simple, since we sometimes need to do
777 // actual work to handle these events whether or not we're in the
778 // foreground (see the Handler code in mSetOptionComplete for
779 // example.)
780 private void showDialogIfForeground(int id) {
781 if (mForeground) {
782 showDialog(id);
783 }
784 }
785
786 private void dismissDialogSafely(int id) {
787 try {
788 dismissDialog(id);
789 } catch (IllegalArgumentException e) {
790 // This is expected in the case where we were in the background
791 // at the time we would normally have shown the dialog, so we didn't
792 // show it.
793 }
794 }
795
Andrew Leeb490d732014-10-27 15:00:41 -0700796 private void saveVoiceMailAndForwardingNumber(
797 String key, VoicemailProviderSettings newSettings) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700798 if (DBG) log("saveVoiceMailAndForwardingNumber: " + newSettings.toString());
Andrew Leeb490d732014-10-27 15:00:41 -0700799 mNewVMNumber = newSettings.getVoicemailNumber();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700800 // empty vm number == clearing the vm number ?
801 if (mNewVMNumber == null) {
802 mNewVMNumber = "";
803 }
804
Andrew Leeb490d732014-10-27 15:00:41 -0700805 mNewFwdSettings = newSettings.getForwardingSettings();
806 if (DBG) log("newFwdNumber "
807 + String.valueOf((mNewFwdSettings != null ? mNewFwdSettings.length : 0))
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700808 + " settings");
809
810 // No fwd settings on CDMA
811 if (mPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
812 if (DBG) log("ignoring forwarding setting since this is CDMA phone");
Andrew Leeb490d732014-10-27 15:00:41 -0700813 mNewFwdSettings = VoicemailProviderSettings.NO_FORWARDING;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700814 }
815
Andrew Leee3c15212014-10-28 13:12:55 -0700816 // Throw a warning if the voicemail is the same and we did not change forwarding.
Andrew Leeb490d732014-10-27 15:00:41 -0700817 if (mNewVMNumber.equals(mOldVmNumber)
818 && mNewFwdSettings == VoicemailProviderSettings.NO_FORWARDING) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700819 showVMDialog(MSG_VM_NOCHANGE);
820 return;
821 }
822
823 maybeSaveSettingsForVoicemailProvider(key, newSettings);
824 mVMChangeCompletedSuccessfully = false;
825 mFwdChangesRequireRollback = false;
826 mVMOrFwdSetError = 0;
827 if (!key.equals(mPreviousVMProviderKey)) {
828 mReadingSettingsForDefaultProvider =
829 mPreviousVMProviderKey.equals(DEFAULT_VM_PROVIDER_KEY);
830 if (DBG) log("Reading current forwarding settings");
Andrew Leeb490d732014-10-27 15:00:41 -0700831 int numSettingsReasons = VoicemailProviderSettings.FORWARDING_SETTINGS_REASONS.length;
832 mForwardingReadResults = new CallForwardInfo[numSettingsReasons];
833 for (int i = 0; i < mForwardingReadResults.length; i++) {
834 mPhone.getCallForwardingOption(
835 VoicemailProviderSettings.FORWARDING_SETTINGS_REASONS[i],
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700836 mGetOptionComplete.obtainMessage(EVENT_FORWARDING_GET_COMPLETED, i, 0));
837 }
838 showDialogIfForeground(VOICEMAIL_FWD_READING_DIALOG);
839 } else {
840 saveVoiceMailAndForwardingNumberStage2();
841 }
842 }
843
844 private final Handler mGetOptionComplete = new Handler() {
845 @Override
846 public void handleMessage(Message msg) {
847 AsyncResult result = (AsyncResult) msg.obj;
848 switch (msg.what) {
849 case EVENT_FORWARDING_GET_COMPLETED:
850 handleForwardingSettingsReadResult(result, msg.arg1);
851 break;
852 }
853 }
854 };
855
856 private void handleForwardingSettingsReadResult(AsyncResult ar, int idx) {
857 if (DBG) Log.d(LOG_TAG, "handleForwardingSettingsReadResult: " + idx);
858 Throwable error = null;
859 if (ar.exception != null) {
860 if (DBG) Log.d(LOG_TAG, "FwdRead: ar.exception=" +
861 ar.exception.getMessage());
862 error = ar.exception;
863 }
864 if (ar.userObj instanceof Throwable) {
865 if (DBG) Log.d(LOG_TAG, "FwdRead: userObj=" +
866 ((Throwable)ar.userObj).getMessage());
867 error = (Throwable)ar.userObj;
868 }
869
870 // We may have already gotten an error and decided to ignore the other results.
871 if (mForwardingReadResults == null) {
872 if (DBG) Log.d(LOG_TAG, "ignoring fwd reading result: " + idx);
873 return;
874 }
875
876 // In case of error ignore other results, show an error dialog
877 if (error != null) {
878 if (DBG) Log.d(LOG_TAG, "Error discovered for fwd read : " + idx);
879 mForwardingReadResults = null;
880 dismissDialogSafely(VOICEMAIL_FWD_READING_DIALOG);
881 showVMDialog(MSG_FW_GET_EXCEPTION);
882 return;
883 }
884
885 // Get the forwarding info
886 final CallForwardInfo cfInfoArray[] = (CallForwardInfo[]) ar.result;
887 CallForwardInfo fi = null;
888 for (int i = 0 ; i < cfInfoArray.length; i++) {
889 if ((cfInfoArray[i].serviceClass & CommandsInterface.SERVICE_CLASS_VOICE) != 0) {
890 fi = cfInfoArray[i];
891 break;
892 }
893 }
894 if (fi == null) {
895
896 // In case we go nothing it means we need this reason disabled
897 // so create a CallForwardInfo for capturing this
898 if (DBG) Log.d(LOG_TAG, "Creating default info for " + idx);
899 fi = new CallForwardInfo();
900 fi.status = 0;
Andrew Leeb490d732014-10-27 15:00:41 -0700901 fi.reason = VoicemailProviderSettings.FORWARDING_SETTINGS_REASONS[idx];
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700902 fi.serviceClass = CommandsInterface.SERVICE_CLASS_VOICE;
903 } else {
904 // if there is not a forwarding number, ensure the entry is set to "not active."
905 if (fi.number == null || fi.number.length() == 0) {
906 fi.status = 0;
907 }
908
909 if (DBG) Log.d(LOG_TAG, "Got " + fi.toString() + " for " + idx);
910 }
911 mForwardingReadResults[idx] = fi;
912
913 // Check if we got all the results already
914 boolean done = true;
915 for (int i = 0; i < mForwardingReadResults.length; i++) {
916 if (mForwardingReadResults[i] == null) {
917 done = false;
918 break;
919 }
920 }
921 if (done) {
922 if (DBG) Log.d(LOG_TAG, "Done receiving fwd info");
923 dismissDialogSafely(VOICEMAIL_FWD_READING_DIALOG);
924 if (mReadingSettingsForDefaultProvider) {
925 maybeSaveSettingsForVoicemailProvider(DEFAULT_VM_PROVIDER_KEY,
Andrew Leeb490d732014-10-27 15:00:41 -0700926 new VoicemailProviderSettings(this.mOldVmNumber,
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700927 mForwardingReadResults));
928 mReadingSettingsForDefaultProvider = false;
929 }
930 saveVoiceMailAndForwardingNumberStage2();
931 } else {
932 if (DBG) Log.d(LOG_TAG, "Not done receiving fwd info");
933 }
934 }
935
936 private CallForwardInfo infoForReason(CallForwardInfo[] infos, int reason) {
937 CallForwardInfo result = null;
938 if (null != infos) {
939 for (CallForwardInfo info : infos) {
940 if (info.reason == reason) {
941 result = info;
942 break;
943 }
944 }
945 }
946 return result;
947 }
948
949 private boolean isUpdateRequired(CallForwardInfo oldInfo,
950 CallForwardInfo newInfo) {
951 boolean result = true;
952 if (0 == newInfo.status) {
953 // If we're disabling a type of forwarding, and it's already
954 // disabled for the account, don't make any change
955 if (oldInfo != null && oldInfo.status == 0) {
956 result = false;
957 }
958 }
959 return result;
960 }
961
962 private void resetForwardingChangeState() {
963 mForwardingChangeResults = new HashMap<Integer, AsyncResult>();
964 mExpectedChangeResultReasons = new HashSet<Integer>();
965 }
966
967 // Called after we are done saving the previous forwarding settings if
968 // we needed.
969 private void saveVoiceMailAndForwardingNumberStage2() {
970 mForwardingChangeResults = null;
971 mVoicemailChangeResult = null;
Andrew Leeb490d732014-10-27 15:00:41 -0700972 if (mNewFwdSettings != VoicemailProviderSettings.NO_FORWARDING) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700973 resetForwardingChangeState();
974 for (int i = 0; i < mNewFwdSettings.length; i++) {
975 CallForwardInfo fi = mNewFwdSettings[i];
976
977 final boolean doUpdate = isUpdateRequired(infoForReason(
978 mForwardingReadResults, fi.reason), fi);
979
980 if (doUpdate) {
981 if (DBG) log("Setting fwd #: " + i + ": " + fi.toString());
982 mExpectedChangeResultReasons.add(i);
983
984 mPhone.setCallForwardingOption(
985 fi.status == 1 ?
986 CommandsInterface.CF_ACTION_REGISTRATION :
987 CommandsInterface.CF_ACTION_DISABLE,
988 fi.reason,
989 fi.number,
990 fi.timeSeconds,
991 mSetOptionComplete.obtainMessage(
992 EVENT_FORWARDING_CHANGED, fi.reason, 0));
993 }
994 }
995 showDialogIfForeground(VOICEMAIL_FWD_SAVING_DIALOG);
996 } else {
997 if (DBG) log("Not touching fwd #");
998 setVMNumberWithCarrier();
999 }
1000 }
1001
1002 private void setVMNumberWithCarrier() {
1003 if (DBG) log("save voicemail #: " + mNewVMNumber);
1004 mPhone.setVoiceMailNumber(
1005 mPhone.getVoiceMailAlphaTag().toString(),
1006 mNewVMNumber,
1007 Message.obtain(mSetOptionComplete, EVENT_VOICEMAIL_CHANGED));
1008 }
1009
1010 /**
1011 * Callback to handle option update completions
1012 */
1013 private final Handler mSetOptionComplete = new Handler() {
1014 @Override
1015 public void handleMessage(Message msg) {
1016 AsyncResult result = (AsyncResult) msg.obj;
1017 boolean done = false;
1018 switch (msg.what) {
1019 case EVENT_VOICEMAIL_CHANGED:
1020 mVoicemailChangeResult = result;
1021 mVMChangeCompletedSuccessfully = checkVMChangeSuccess() == null;
1022 if (DBG) log("VM change complete msg, VM change done = " +
1023 String.valueOf(mVMChangeCompletedSuccessfully));
1024 done = true;
1025 break;
1026 case EVENT_FORWARDING_CHANGED:
1027 mForwardingChangeResults.put(msg.arg1, result);
1028 if (result.exception != null) {
1029 Log.w(LOG_TAG, "Error in setting fwd# " + msg.arg1 + ": " +
1030 result.exception.getMessage());
1031 } else {
1032 if (DBG) log("Success in setting fwd# " + msg.arg1);
1033 }
1034 final boolean completed = checkForwardingCompleted();
1035 if (completed) {
1036 if (checkFwdChangeSuccess() == null) {
1037 if (DBG) log("Overall fwd changes completed ok, starting vm change");
1038 setVMNumberWithCarrier();
1039 } else {
1040 Log.w(LOG_TAG, "Overall fwd changes completed in failure. " +
1041 "Check if we need to try rollback for some settings.");
1042 mFwdChangesRequireRollback = false;
1043 Iterator<Map.Entry<Integer,AsyncResult>> it =
1044 mForwardingChangeResults.entrySet().iterator();
1045 while (it.hasNext()) {
1046 Map.Entry<Integer,AsyncResult> entry = it.next();
1047 if (entry.getValue().exception == null) {
1048 // If at least one succeeded we have to revert
1049 Log.i(LOG_TAG, "Rollback will be required");
1050 mFwdChangesRequireRollback = true;
1051 break;
1052 }
1053 }
1054 if (!mFwdChangesRequireRollback) {
1055 Log.i(LOG_TAG, "No rollback needed.");
1056 }
1057 done = true;
1058 }
1059 }
1060 break;
1061 default:
1062 // TODO: should never reach this, may want to throw exception
1063 }
1064 if (done) {
1065 if (DBG) log("All VM provider related changes done");
1066 if (mForwardingChangeResults != null) {
1067 dismissDialogSafely(VOICEMAIL_FWD_SAVING_DIALOG);
1068 }
1069 handleSetVMOrFwdMessage();
1070 }
1071 }
1072 };
1073
1074 /**
1075 * Callback to handle option revert completions
1076 */
1077 private final Handler mRevertOptionComplete = new Handler() {
1078 @Override
1079 public void handleMessage(Message msg) {
1080 AsyncResult result = (AsyncResult) msg.obj;
1081 switch (msg.what) {
1082 case EVENT_VOICEMAIL_CHANGED:
1083 mVoicemailChangeResult = result;
1084 if (DBG) log("VM revert complete msg");
1085 break;
1086 case EVENT_FORWARDING_CHANGED:
1087 mForwardingChangeResults.put(msg.arg1, result);
1088 if (result.exception != null) {
1089 if (DBG) log("Error in reverting fwd# " + msg.arg1 + ": " +
1090 result.exception.getMessage());
1091 } else {
1092 if (DBG) log("Success in reverting fwd# " + msg.arg1);
1093 }
1094 if (DBG) log("FWD revert complete msg ");
1095 break;
1096 default:
1097 // TODO: should never reach this, may want to throw exception
1098 }
1099 final boolean done =
1100 (!mVMChangeCompletedSuccessfully || mVoicemailChangeResult != null) &&
1101 (!mFwdChangesRequireRollback || checkForwardingCompleted());
1102 if (done) {
1103 if (DBG) log("All VM reverts done");
1104 dismissDialogSafely(VOICEMAIL_REVERTING_DIALOG);
1105 onRevertDone();
1106 }
1107 }
1108 };
1109
1110 /**
1111 * @return true if forwarding change has completed
1112 */
1113 private boolean checkForwardingCompleted() {
1114 boolean result;
1115 if (mForwardingChangeResults == null) {
1116 result = true;
1117 } else {
1118 // return true iff there is a change result for every reason for
1119 // which we expected a result
1120 result = true;
1121 for (Integer reason : mExpectedChangeResultReasons) {
1122 if (mForwardingChangeResults.get(reason) == null) {
1123 result = false;
1124 break;
1125 }
1126 }
1127 }
1128 return result;
1129 }
1130 /**
1131 * @return error string or null if successful
1132 */
1133 private String checkFwdChangeSuccess() {
1134 String result = null;
1135 Iterator<Map.Entry<Integer,AsyncResult>> it =
1136 mForwardingChangeResults.entrySet().iterator();
1137 while (it.hasNext()) {
1138 Map.Entry<Integer,AsyncResult> entry = it.next();
1139 Throwable exception = entry.getValue().exception;
1140 if (exception != null) {
1141 result = exception.getMessage();
1142 if (result == null) {
1143 result = "";
1144 }
1145 break;
1146 }
1147 }
1148 return result;
1149 }
1150
1151 /**
1152 * @return error string or null if successful
1153 */
1154 private String checkVMChangeSuccess() {
1155 if (mVoicemailChangeResult.exception != null) {
1156 final String msg = mVoicemailChangeResult.exception.getMessage();
1157 if (msg == null) {
1158 return "";
1159 }
1160 return msg;
1161 }
1162 return null;
1163 }
1164
1165 private void handleSetVMOrFwdMessage() {
1166 if (DBG) {
1167 log("handleSetVMMessage: set VM request complete");
1168 }
1169 boolean success = true;
1170 boolean fwdFailure = false;
1171 String exceptionMessage = "";
1172 if (mForwardingChangeResults != null) {
1173 exceptionMessage = checkFwdChangeSuccess();
1174 if (exceptionMessage != null) {
1175 success = false;
1176 fwdFailure = true;
1177 }
1178 }
1179 if (success) {
1180 exceptionMessage = checkVMChangeSuccess();
1181 if (exceptionMessage != null) {
1182 success = false;
1183 }
1184 }
1185 if (success) {
1186 if (DBG) log("change VM success!");
1187 handleVMAndFwdSetSuccess(MSG_VM_OK);
1188 } else {
1189 if (fwdFailure) {
1190 Log.w(LOG_TAG, "Failed to change fowarding setting. Reason: " + exceptionMessage);
1191 handleVMOrFwdSetError(MSG_FW_SET_EXCEPTION);
1192 } else {
1193 Log.w(LOG_TAG, "Failed to change voicemail. Reason: " + exceptionMessage);
1194 handleVMOrFwdSetError(MSG_VM_EXCEPTION);
1195 }
1196 }
1197 }
1198
1199 /**
1200 * Called when Voicemail Provider or its forwarding settings failed. Rolls back partly made
1201 * changes to those settings and show "failure" dialog.
1202 *
1203 * @param msgId Message ID used for the specific error case. {@link #MSG_FW_SET_EXCEPTION} or
1204 * {@link #MSG_VM_EXCEPTION}
1205 */
1206 private void handleVMOrFwdSetError(int msgId) {
1207 if (mChangingVMorFwdDueToProviderChange) {
1208 mVMOrFwdSetError = msgId;
1209 mChangingVMorFwdDueToProviderChange = false;
1210 switchToPreviousVoicemailProvider();
1211 return;
1212 }
1213 mChangingVMorFwdDueToProviderChange = false;
1214 showVMDialog(msgId);
1215 updateVoiceNumberField();
1216 }
1217
1218 /**
1219 * Called when Voicemail Provider and its forwarding settings were successfully finished.
1220 * This updates a bunch of variables and show "success" dialog.
1221 */
1222 private void handleVMAndFwdSetSuccess(int msg) {
1223 if (DBG) {
1224 log("handleVMAndFwdSetSuccess(). current voicemail provider key: "
1225 + getCurrentVoicemailProviderKey());
1226 }
1227 mPreviousVMProviderKey = getCurrentVoicemailProviderKey();
1228 mChangingVMorFwdDueToProviderChange = false;
1229 showVMDialog(msg);
1230 updateVoiceNumberField();
1231 }
1232
1233 /**
1234 * Update the voicemail number from what we've recorded on the sim.
1235 */
1236 private void updateVoiceNumberField() {
1237 if (DBG) {
1238 log("updateVoiceNumberField(). mSubMenuVoicemailSettings=" + mSubMenuVoicemailSettings);
1239 }
1240 if (mSubMenuVoicemailSettings == null) {
1241 return;
1242 }
1243
1244 mOldVmNumber = mPhone.getVoiceMailNumber();
1245 if (mOldVmNumber == null) {
1246 mOldVmNumber = "";
1247 }
1248 mSubMenuVoicemailSettings.setPhoneNumber(mOldVmNumber);
1249 final String summary = (mOldVmNumber.length() > 0) ? mOldVmNumber :
1250 getString(R.string.voicemail_number_not_set);
1251 mSubMenuVoicemailSettings.setSummary(summary);
1252 }
1253
1254 /*
1255 * Helper Methods for Activity class.
1256 * The initial query commands are split into two pieces now
1257 * for individual expansion. This combined with the ability
1258 * to cancel queries allows for a much better user experience,
1259 * and also ensures that the user only waits to update the
1260 * data that is relevant.
1261 */
1262
1263 @Override
1264 protected void onPrepareDialog(int id, Dialog dialog) {
1265 super.onPrepareDialog(id, dialog);
1266 mCurrentDialogId = id;
1267 }
1268
1269 // dialog creation method, called by showDialog()
1270 @Override
1271 protected Dialog onCreateDialog(int id) {
1272 if ((id == VM_RESPONSE_ERROR) || (id == VM_NOCHANGE_ERROR) ||
1273 (id == FW_SET_RESPONSE_ERROR) || (id == FW_GET_RESPONSE_ERROR) ||
1274 (id == VOICEMAIL_DIALOG_CONFIRM)) {
1275
1276 AlertDialog.Builder b = new AlertDialog.Builder(this);
1277
1278 int msgId;
1279 int titleId = R.string.error_updating_title;
1280 switch (id) {
1281 case VOICEMAIL_DIALOG_CONFIRM:
1282 msgId = R.string.vm_changed;
1283 titleId = R.string.voicemail;
1284 // Set Button 2
1285 b.setNegativeButton(R.string.close_dialog, this);
1286 break;
1287 case VM_NOCHANGE_ERROR:
1288 // even though this is technically an error,
1289 // keep the title friendly.
1290 msgId = R.string.no_change;
1291 titleId = R.string.voicemail;
1292 // Set Button 2
1293 b.setNegativeButton(R.string.close_dialog, this);
1294 break;
1295 case VM_RESPONSE_ERROR:
1296 msgId = R.string.vm_change_failed;
1297 // Set Button 1
1298 b.setPositiveButton(R.string.close_dialog, this);
1299 break;
1300 case FW_SET_RESPONSE_ERROR:
1301 msgId = R.string.fw_change_failed;
1302 // Set Button 1
1303 b.setPositiveButton(R.string.close_dialog, this);
1304 break;
1305 case FW_GET_RESPONSE_ERROR:
1306 msgId = R.string.fw_get_in_vm_failed;
1307 b.setPositiveButton(R.string.alert_dialog_yes, this);
1308 b.setNegativeButton(R.string.alert_dialog_no, this);
1309 break;
1310 default:
1311 msgId = R.string.exception_error;
1312 // Set Button 3, tells the activity that the error is
1313 // not recoverable on dialog exit.
1314 b.setNeutralButton(R.string.close_dialog, this);
1315 break;
1316 }
1317
1318 b.setTitle(getText(titleId));
1319 String message = getText(msgId).toString();
1320 b.setMessage(message);
1321 b.setCancelable(false);
1322 AlertDialog dialog = b.create();
1323
1324 // make the dialog more obvious by bluring the background.
1325 dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
1326
1327 return dialog;
1328 } else if (id == VOICEMAIL_FWD_SAVING_DIALOG || id == VOICEMAIL_FWD_READING_DIALOG ||
1329 id == VOICEMAIL_REVERTING_DIALOG) {
1330 ProgressDialog dialog = new ProgressDialog(this);
1331 dialog.setTitle(getText(R.string.updating_title));
1332 dialog.setIndeterminate(true);
1333 dialog.setCancelable(false);
1334 dialog.setMessage(getText(
1335 id == VOICEMAIL_FWD_SAVING_DIALOG ? R.string.updating_settings :
1336 (id == VOICEMAIL_REVERTING_DIALOG ? R.string.reverting_settings :
1337 R.string.reading_settings)));
1338 return dialog;
1339 }
1340
1341
1342 return null;
1343 }
1344
1345 // This is a method implemented for DialogInterface.OnClickListener.
1346 // Used with the error dialog to close the app, voicemail dialog to just dismiss.
1347 // Close button is mapped to BUTTON_POSITIVE for the errors that close the activity,
1348 // while those that are mapped to BUTTON_NEUTRAL only move the preference focus.
1349 public void onClick(DialogInterface dialog, int which) {
1350 dialog.dismiss();
1351 switch (which){
1352 case DialogInterface.BUTTON_NEUTRAL:
1353 if (DBG) log("Neutral button");
1354 break;
1355 case DialogInterface.BUTTON_NEGATIVE:
1356 if (DBG) log("Negative button");
1357 if (mCurrentDialogId == FW_GET_RESPONSE_ERROR) {
1358 // We failed to get current forwarding settings and the user
1359 // does not wish to continue.
1360 switchToPreviousVoicemailProvider();
1361 }
1362 break;
1363 case DialogInterface.BUTTON_POSITIVE:
1364 if (DBG) log("Positive button");
1365 if (mCurrentDialogId == FW_GET_RESPONSE_ERROR) {
1366 // We failed to get current forwarding settings but the user
1367 // wishes to continue changing settings to the new vm provider
1368 saveVoiceMailAndForwardingNumberStage2();
1369 } else {
1370 finish();
1371 }
1372 return;
1373 default:
1374 // just let the dialog close and go back to the input
1375 }
1376 // In all dialogs, all buttons except BUTTON_POSITIVE lead to the end of user interaction
1377 // with settings UI. If we were called to explicitly configure voice mail then
1378 // we finish the settings activity here to come back to whatever the user was doing.
1379 if (getIntent().getAction().equals(ACTION_ADD_VOICEMAIL)) {
1380 finish();
1381 }
1382 }
1383
1384 // set the app state with optional status.
1385 private void showVMDialog(int msgStatus) {
1386 switch (msgStatus) {
1387 // It's a bit worrisome to punt in the error cases here when we're
1388 // not in the foreground; maybe toast instead?
1389 case MSG_VM_EXCEPTION:
1390 showDialogIfForeground(VM_RESPONSE_ERROR);
1391 break;
1392 case MSG_FW_SET_EXCEPTION:
1393 showDialogIfForeground(FW_SET_RESPONSE_ERROR);
1394 break;
1395 case MSG_FW_GET_EXCEPTION:
1396 showDialogIfForeground(FW_GET_RESPONSE_ERROR);
1397 break;
1398 case MSG_VM_NOCHANGE:
1399 showDialogIfForeground(VM_NOCHANGE_ERROR);
1400 break;
1401 case MSG_VM_OK:
1402 showDialogIfForeground(VOICEMAIL_DIALOG_CONFIRM);
1403 break;
1404 case MSG_OK:
1405 default:
1406 // This should never happen.
1407 }
1408 }
1409
1410 /*
1411 * Activity class methods
1412 */
1413
1414 @Override
1415 protected void onCreate(Bundle icicle) {
1416 super.onCreate(icicle);
1417 if (DBG) log("onCreate(). Intent: " + getIntent());
1418 mPhone = PhoneGlobals.getPhone();
Tyler Gunnbaee2952014-09-10 16:01:02 -07001419 mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
1420
1421 // create intent to bring up contact list
1422 mContactListIntent = new Intent(Intent.ACTION_GET_CONTENT);
1423 mContactListIntent.setType(android.provider.Contacts.Phones.CONTENT_ITEM_TYPE);
1424
1425 mVoicemailRingtoneLookupRunnable = new Runnable() {
1426 @Override
1427 public void run() {
1428 if (mVoicemailNotificationRingtone != null) {
1429 SettingsUtil.updateRingtoneName(
1430 mPhone.getContext(),
1431 mVoicemailRingtoneLookupComplete,
1432 RingtoneManager.TYPE_NOTIFICATION,
1433 mVoicemailNotificationRingtone,
1434 MSG_UPDATE_VOICEMAIL_RINGTONE_SUMMARY);
1435 }
1436 }
1437 };
1438
Tyler Gunnbaee2952014-09-10 16:01:02 -07001439 // Show the voicemail preference in onResume if the calling intent specifies the
1440 // ACTION_ADD_VOICEMAIL action.
1441 mShowVoicemailPreference = (icicle == null) &&
1442 getIntent().getAction().equals(ACTION_ADD_VOICEMAIL);
1443 }
1444
1445 private void initPhoneAccountPreferences() {
Andrew Leece8ae2a2014-09-10 10:41:48 -07001446 mPhoneAccountSettingsPreference = findPreference(PHONE_ACCOUNT_SETTINGS_KEY);
Tyler Gunnbaee2952014-09-10 16:01:02 -07001447
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001448 TelecomManager telecomManager = TelecomManager.from(this);
Andrew Lee93c345f2014-10-27 15:25:07 -07001449 TelephonyManager telephonyManager =
1450 (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
Tyler Gunnbaee2952014-09-10 16:01:02 -07001451
Andrew Lee93c345f2014-10-27 15:25:07 -07001452 if ((telecomManager.getSimCallManagers().isEmpty() && !SipUtil.isVoipSupported(this))
1453 || telephonyManager.getPhoneCount() > 1) {
Andrew Leece8ae2a2014-09-10 10:41:48 -07001454 getPreferenceScreen().removePreference(mPhoneAccountSettingsPreference);
Tyler Gunnbaee2952014-09-10 16:01:02 -07001455 }
1456 }
1457
1458 private boolean canLaunchIntent(Intent intent) {
1459 PackageManager pm = getPackageManager();
1460 return pm.resolveActivity(intent, PackageManager.GET_ACTIVITIES) != null;
1461 }
1462
Tyler Gunnbaee2952014-09-10 16:01:02 -07001463 @Override
1464 protected void onResume() {
1465 super.onResume();
1466 mForeground = true;
1467
1468 PreferenceScreen preferenceScreen = getPreferenceScreen();
1469 if (preferenceScreen != null) {
1470 preferenceScreen.removeAll();
1471 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001472
1473 addPreferencesFromResource(R.xml.call_feature_setting);
Andrew Leedb2fe562014-09-03 15:40:43 -07001474 initPhoneAccountPreferences();
1475
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001476 // get buttons
1477 PreferenceScreen prefSet = getPreferenceScreen();
Andrew Lee64a7d792014-10-15 17:38:38 -07001478 mSubMenuVoicemailSettings = (EditPhoneNumberPreference) findPreference(BUTTON_VOICEMAIL_KEY);
1479 mSubMenuVoicemailSettings.setParentActivity(this, VOICEMAIL_PREF_ID, this);
1480 mSubMenuVoicemailSettings.setDialogOnClosedListener(this);
1481 mSubMenuVoicemailSettings.setDialogTitle(R.string.voicemail_settings_number_label);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001482
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001483 mButtonDTMF = (ListPreference) findPreference(BUTTON_DTMF_KEY);
1484 mButtonAutoRetry = (CheckBoxPreference) findPreference(BUTTON_RETRY_KEY);
1485 mButtonHAC = (CheckBoxPreference) findPreference(BUTTON_HAC_KEY);
1486 mButtonTTY = (ListPreference) findPreference(BUTTON_TTY_KEY);
1487 mVoicemailProviders = (ListPreference) findPreference(BUTTON_VOICEMAIL_PROVIDER_KEY);
Andrew Leedf14ead2014-10-17 14:22:52 -07001488 CheckBoxPreference mEnableVideoCalling =
1489 (CheckBoxPreference) findPreference(ENABLE_VIDEO_CALLING_KEY);
Andrew Lee2170a972014-08-13 18:13:01 -07001490
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001491 if (mVoicemailProviders != null) {
1492 mVoicemailProviders.setOnPreferenceChangeListener(this);
Andrew Lee97708a42014-09-25 12:39:07 -07001493 mVoicemailSettingsScreen =
1494 (PreferenceScreen) findPreference(VOICEMAIL_SETTING_SCREEN_PREF_KEY);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001495 mVoicemailSettings = (PreferenceScreen)findPreference(BUTTON_VOICEMAIL_SETTING_KEY);
1496 mVoicemailNotificationRingtone =
1497 findPreference(BUTTON_VOICEMAIL_NOTIFICATION_RINGTONE_KEY);
1498 mVoicemailNotificationVibrate =
1499 (CheckBoxPreference) findPreference(BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY);
1500 initVoiceMailProviders();
1501 }
1502
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001503
Andrew Lee64a7d792014-10-15 17:38:38 -07001504 if (getResources().getBoolean(R.bool.dtmf_type_enabled)) {
1505 mButtonDTMF.setOnPreferenceChangeListener(this);
1506 int dtmf = Settings.System.getInt(getContentResolver(),
1507 Settings.System.DTMF_TONE_TYPE_WHEN_DIALING, Constants.DTMF_TONE_TYPE_NORMAL);
1508 mButtonDTMF.setValueIndex(dtmf);
1509 } else {
1510 prefSet.removePreference(mButtonDTMF);
1511 mButtonDTMF = null;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001512 }
1513
Andrew Lee64a7d792014-10-15 17:38:38 -07001514 if (getResources().getBoolean(R.bool.auto_retry_enabled)) {
1515 mButtonAutoRetry.setOnPreferenceChangeListener(this);
1516 int autoretry = Settings.Global.getInt(
1517 getContentResolver(), Settings.Global.CALL_AUTO_RETRY, 0);
1518 mButtonAutoRetry.setChecked(autoretry != 0);
1519 } else {
1520 prefSet.removePreference(mButtonAutoRetry);
1521 mButtonAutoRetry = null;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001522 }
1523
Andrew Lee64a7d792014-10-15 17:38:38 -07001524 if (getResources().getBoolean(R.bool.hac_enabled)) {
1525 mButtonHAC.setOnPreferenceChangeListener(this);
1526 int hac = Settings.System.getInt(getContentResolver(), Settings.System.HEARING_AID, 0);
1527 mButtonHAC.setChecked(hac != 0);
1528 } else {
1529 prefSet.removePreference(mButtonHAC);
1530 mButtonHAC = null;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001531 }
1532
Andrew Lee64a7d792014-10-15 17:38:38 -07001533 TelecomManager telecomManager = TelecomManager.from(this);
1534 if (telecomManager != null && telecomManager.isTtySupported()) {
1535 mButtonTTY.setOnPreferenceChangeListener(this);
1536 int settingsTtyMode = Settings.Secure.getInt(getContentResolver(),
1537 Settings.Secure.PREFERRED_TTY_MODE,
1538 TelecomManager.TTY_MODE_OFF);
1539 mButtonTTY.setValue(Integer.toString(settingsTtyMode));
1540 updatePreferredTtyModeSummary(settingsTtyMode);
1541 } else {
1542 prefSet.removePreference(mButtonTTY);
1543 mButtonTTY = null;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001544 }
1545
1546 if (!getResources().getBoolean(R.bool.world_phone)) {
1547 Preference options = prefSet.findPreference(BUTTON_CDMA_OPTIONS);
Andrew Lee2170a972014-08-13 18:13:01 -07001548 if (options != null) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001549 prefSet.removePreference(options);
Andrew Lee2170a972014-08-13 18:13:01 -07001550 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001551 options = prefSet.findPreference(BUTTON_GSM_UMTS_OPTIONS);
Andrew Lee2170a972014-08-13 18:13:01 -07001552 if (options != null) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001553 prefSet.removePreference(options);
Andrew Lee2170a972014-08-13 18:13:01 -07001554 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001555
1556 int phoneType = mPhone.getPhoneType();
1557 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1558 Preference fdnButton = prefSet.findPreference(BUTTON_FDN_KEY);
Andrew Lee2170a972014-08-13 18:13:01 -07001559 if (fdnButton != null) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001560 prefSet.removePreference(fdnButton);
Andrew Lee2170a972014-08-13 18:13:01 -07001561 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001562 if (!getResources().getBoolean(R.bool.config_voice_privacy_disable)) {
1563 addPreferencesFromResource(R.xml.cdma_call_privacy);
1564 }
1565 } else if (phoneType == PhoneConstants.PHONE_TYPE_GSM) {
Andrew Lee2170a972014-08-13 18:13:01 -07001566 if (getResources().getBoolean(R.bool.config_additional_call_setting)) {
Etan Cohen0ca1c802014-07-07 15:35:48 -07001567 addPreferencesFromResource(R.xml.gsm_umts_call_options);
1568 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001569 } else {
1570 throw new IllegalStateException("Unexpected phone type: " + phoneType);
1571 }
1572 }
1573
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001574 // check the intent that started this activity and pop up the voicemail
1575 // dialog if we've been asked to.
1576 // If we have at least one non default VM provider registered then bring up
1577 // the selection for the VM provider, otherwise bring up a VM number dialog.
1578 // We only bring up the dialog the first time we are called (not after orientation change)
Tyler Gunnbaee2952014-09-10 16:01:02 -07001579 if (mShowVoicemailPreference && mVoicemailProviders != null) {
1580 if (DBG) {
1581 log("ACTION_ADD_VOICEMAIL Intent is thrown. current VM data size: "
1582 + mVMProvidersData.size());
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001583 }
Tyler Gunnbaee2952014-09-10 16:01:02 -07001584 if (mVMProvidersData.size() > 1) {
1585 simulatePreferenceClick(mVoicemailProviders);
1586 } else {
1587 onPreferenceChange(mVoicemailProviders, DEFAULT_VM_PROVIDER_KEY);
1588 mVoicemailProviders.setValue(DEFAULT_VM_PROVIDER_KEY);
1589 }
1590 mShowVoicemailPreference = false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001591 }
Tyler Gunnbaee2952014-09-10 16:01:02 -07001592
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001593 updateVoiceNumberField();
1594 mVMProviderSettingsForced = false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001595
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001596 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(
1597 mPhone.getContext());
1598 if (migrateVoicemailVibrationSettingsIfNeeded(prefs)) {
1599 mVoicemailNotificationVibrate.setChecked(prefs.getBoolean(
1600 BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY, false));
1601 }
1602
Andrew Lee77527ac2014-10-21 16:57:39 -07001603 if (ImsUtil.isImsEnabled(mPhone.getContext()) && ENABLE_VT_FLAG) {
1604 mEnableVideoCalling.setChecked(
1605 PhoneGlobals.getInstance().phoneMgr.isVideoCallingEnabled());
1606 mEnableVideoCalling.setOnPreferenceChangeListener(this);
1607 } else {
1608 prefSet.removePreference(mEnableVideoCalling);
1609 }
Andrew Leedf14ead2014-10-17 14:22:52 -07001610
Andrew Lee2170a972014-08-13 18:13:01 -07001611 // Look up the voicemail ringtone name asynchronously and update its preference.
1612 new Thread(mVoicemailRingtoneLookupRunnable).start();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001613 }
1614
1615 // Migrate settings from BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_WHEN_KEY to
1616 // BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY, if the latter does not exist.
1617 // Returns true if migration was performed.
1618 public static boolean migrateVoicemailVibrationSettingsIfNeeded(SharedPreferences prefs) {
1619 if (!prefs.contains(BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY)) {
1620 String vibrateWhen = prefs.getString(
1621 BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_WHEN_KEY, VOICEMAIL_VIBRATION_NEVER);
1622 // If vibrateWhen is always, then voicemailVibrate should be True.
1623 // otherwise if vibrateWhen is "only in silent mode", or "never", then
1624 // voicemailVibrate = False.
1625 boolean voicemailVibrate = vibrateWhen.equals(VOICEMAIL_VIBRATION_ALWAYS);
1626 final SharedPreferences.Editor editor = prefs.edit();
1627 editor.putBoolean(BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY, voicemailVibrate);
1628 editor.commit();
1629 return true;
1630 }
1631 return false;
1632 }
1633
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001634 private boolean isAirplaneModeOn() {
1635 return Settings.System.getInt(getContentResolver(),
1636 Settings.System.AIRPLANE_MODE_ON, 0) != 0;
1637 }
1638
1639 private void handleTTYChange(Preference preference, Object objValue) {
1640 int buttonTtyMode;
1641 buttonTtyMode = Integer.valueOf((String) objValue).intValue();
1642 int settingsTtyMode = android.provider.Settings.Secure.getInt(
1643 getContentResolver(),
Sailesh Nepalbf900542014-07-15 16:18:32 -07001644 android.provider.Settings.Secure.PREFERRED_TTY_MODE,
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001645 TelecomManager.TTY_MODE_OFF);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001646 if (DBG) log("handleTTYChange: requesting set TTY mode enable (TTY) to" +
1647 Integer.toString(buttonTtyMode));
1648
1649 if (buttonTtyMode != settingsTtyMode) {
1650 switch(buttonTtyMode) {
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001651 case TelecomManager.TTY_MODE_OFF:
1652 case TelecomManager.TTY_MODE_FULL:
1653 case TelecomManager.TTY_MODE_HCO:
1654 case TelecomManager.TTY_MODE_VCO:
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001655 android.provider.Settings.Secure.putInt(getContentResolver(),
1656 android.provider.Settings.Secure.PREFERRED_TTY_MODE, buttonTtyMode);
1657 break;
1658 default:
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001659 buttonTtyMode = TelecomManager.TTY_MODE_OFF;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001660 }
1661
1662 mButtonTTY.setValue(Integer.toString(buttonTtyMode));
1663 updatePreferredTtyModeSummary(buttonTtyMode);
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001664 Intent ttyModeChanged = new Intent(TelecomManager.ACTION_TTY_PREFERRED_MODE_CHANGED);
1665 ttyModeChanged.putExtra(TelecomManager.EXTRA_TTY_PREFERRED_MODE, buttonTtyMode);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001666 sendBroadcastAsUser(ttyModeChanged, UserHandle.ALL);
1667 }
1668 }
1669
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001670 private void updatePreferredTtyModeSummary(int TtyMode) {
1671 String [] txts = getResources().getStringArray(R.array.tty_mode_entries);
1672 switch(TtyMode) {
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001673 case TelecomManager.TTY_MODE_OFF:
1674 case TelecomManager.TTY_MODE_HCO:
1675 case TelecomManager.TTY_MODE_VCO:
1676 case TelecomManager.TTY_MODE_FULL:
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001677 mButtonTTY.setSummary(txts[TtyMode]);
1678 break;
1679 default:
1680 mButtonTTY.setEnabled(false);
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001681 mButtonTTY.setSummary(txts[TelecomManager.TTY_MODE_OFF]);
Sailesh Nepalbf900542014-07-15 16:18:32 -07001682 break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001683 }
1684 }
1685
1686 private static void log(String msg) {
1687 Log.d(LOG_TAG, msg);
1688 }
1689
1690 /**
1691 * Updates the look of the VM preference widgets based on current VM provider settings.
1692 * Note that the provider name is loaded form the found activity via loadLabel in
1693 * {@link #initVoiceMailProviders()} in order for it to be localizable.
1694 */
1695 private void updateVMPreferenceWidgets(String currentProviderSetting) {
1696 final String key = currentProviderSetting;
1697 final VoiceMailProvider provider = mVMProvidersData.get(key);
1698
1699 /* This is the case when we are coming up on a freshly wiped phone and there is no
1700 persisted value for the list preference mVoicemailProviders.
1701 In this case we want to show the UI asking the user to select a voicemail provider as
1702 opposed to silently falling back to default one. */
1703 if (provider == null) {
1704 if (DBG) {
1705 log("updateVMPreferenceWidget: provider for the key \"" + key + "\" is null.");
1706 }
1707 mVoicemailProviders.setSummary(getString(R.string.sum_voicemail_choose_provider));
1708 mVoicemailSettings.setEnabled(false);
1709 mVoicemailSettings.setIntent(null);
1710
1711 mVoicemailNotificationVibrate.setEnabled(false);
1712 } else {
1713 if (DBG) {
1714 log("updateVMPreferenceWidget: provider for the key \"" + key + "\".."
1715 + "name: " + provider.name
1716 + ", intent: " + provider.intent);
1717 }
1718 final String providerName = provider.name;
1719 mVoicemailProviders.setSummary(providerName);
1720 mVoicemailSettings.setEnabled(true);
1721 mVoicemailSettings.setIntent(provider.intent);
1722
1723 mVoicemailNotificationVibrate.setEnabled(true);
1724 }
1725 }
1726
1727 /**
1728 * Enumerates existing VM providers and puts their data into the list and populates
1729 * the preference list objects with their names.
1730 * In case we are called with ACTION_ADD_VOICEMAIL intent the intent may have
1731 * an extra string called IGNORE_PROVIDER_EXTRA with "package.activityName" of the provider
1732 * which should be hidden when we bring up the list of possible VM providers to choose.
1733 */
1734 private void initVoiceMailProviders() {
1735 if (DBG) log("initVoiceMailProviders()");
1736 mPerProviderSavedVMNumbers =
1737 this.getApplicationContext().getSharedPreferences(
1738 VM_NUMBERS_SHARED_PREFERENCES_NAME, MODE_PRIVATE);
1739
1740 String providerToIgnore = null;
1741 if (getIntent().getAction().equals(ACTION_ADD_VOICEMAIL)) {
1742 if (getIntent().hasExtra(IGNORE_PROVIDER_EXTRA)) {
1743 providerToIgnore = getIntent().getStringExtra(IGNORE_PROVIDER_EXTRA);
1744 }
1745 if (DBG) log("Found ACTION_ADD_VOICEMAIL. providerToIgnore=" + providerToIgnore);
1746 if (providerToIgnore != null) {
1747 // IGNORE_PROVIDER_EXTRA implies we want to remove the choice from the list.
1748 deleteSettingsForVoicemailProvider(providerToIgnore);
1749 }
1750 }
1751
1752 mVMProvidersData.clear();
1753
1754 // Stick the default element which is always there
1755 final String myCarrier = getString(R.string.voicemail_default);
1756 mVMProvidersData.put(DEFAULT_VM_PROVIDER_KEY, new VoiceMailProvider(myCarrier, null));
1757
1758 // Enumerate providers
1759 PackageManager pm = getPackageManager();
1760 Intent intent = new Intent();
1761 intent.setAction(ACTION_CONFIGURE_VOICEMAIL);
1762 List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
1763 int len = resolveInfos.size() + 1; // +1 for the default choice we will insert.
1764
1765 // Go through the list of discovered providers populating the data map
1766 // skip the provider we were instructed to ignore if there was one
1767 for (int i = 0; i < resolveInfos.size(); i++) {
1768 final ResolveInfo ri= resolveInfos.get(i);
1769 final ActivityInfo currentActivityInfo = ri.activityInfo;
1770 final String key = makeKeyForActivity(currentActivityInfo);
1771 if (key.equals(providerToIgnore)) {
1772 if (DBG) log("Ignoring key: " + key);
1773 len--;
1774 continue;
1775 }
1776 if (DBG) log("Loading key: " + key);
1777 final String nameForDisplay = ri.loadLabel(pm).toString();
1778 Intent providerIntent = new Intent();
1779 providerIntent.setAction(ACTION_CONFIGURE_VOICEMAIL);
1780 providerIntent.setClassName(currentActivityInfo.packageName,
1781 currentActivityInfo.name);
1782 if (DBG) {
1783 log("Store loaded VoiceMailProvider. key: " + key
1784 + " -> name: " + nameForDisplay + ", intent: " + providerIntent);
1785 }
1786 mVMProvidersData.put(
1787 key,
1788 new VoiceMailProvider(nameForDisplay, providerIntent));
1789
1790 }
1791
1792 // Now we know which providers to display - create entries and values array for
1793 // the list preference
1794 String [] entries = new String [len];
1795 String [] values = new String [len];
1796 entries[0] = myCarrier;
1797 values[0] = DEFAULT_VM_PROVIDER_KEY;
1798 int entryIdx = 1;
1799 for (int i = 0; i < resolveInfos.size(); i++) {
1800 final String key = makeKeyForActivity(resolveInfos.get(i).activityInfo);
1801 if (!mVMProvidersData.containsKey(key)) {
1802 continue;
1803 }
1804 entries[entryIdx] = mVMProvidersData.get(key).name;
1805 values[entryIdx] = key;
1806 entryIdx++;
1807 }
1808
1809 // ListPreference is now updated.
1810 mVoicemailProviders.setEntries(entries);
1811 mVoicemailProviders.setEntryValues(values);
1812
1813 // Remember the current Voicemail Provider key as a "previous" key. This will be used
1814 // when we fail to update Voicemail Provider, which requires rollback.
1815 // We will update this when the VM Provider setting is successfully updated.
1816 mPreviousVMProviderKey = getCurrentVoicemailProviderKey();
1817 if (DBG) log("Set up the first mPreviousVMProviderKey: " + mPreviousVMProviderKey);
1818
1819 // Finally update the preference texts.
1820 updateVMPreferenceWidgets(mPreviousVMProviderKey);
1821 }
1822
1823 private String makeKeyForActivity(ActivityInfo ai) {
1824 return ai.name;
1825 }
1826
1827 /**
1828 * Simulates user clicking on a passed preference.
1829 * Usually needed when the preference is a dialog preference and we want to invoke
1830 * a dialog for this preference programmatically.
Santos Cordonda120f42014-08-06 04:44:34 -07001831 * TODO: figure out if there is a cleaner way to cause preference dlg to come up
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001832 */
1833 private void simulatePreferenceClick(Preference preference) {
1834 // Go through settings until we find our setting
1835 // and then simulate a click on it to bring up the dialog
1836 final ListAdapter adapter = getPreferenceScreen().getRootAdapter();
1837 for (int idx = 0; idx < adapter.getCount(); idx++) {
1838 if (adapter.getItem(idx) == preference) {
1839 getPreferenceScreen().onItemClick(this.getListView(),
1840 null, idx, adapter.getItemId(idx));
1841 break;
1842 }
1843 }
1844 }
1845
1846 /**
1847 * Saves new VM provider settings associating them with the currently selected
1848 * provider if settings are different than the ones already stored for this
1849 * provider.
1850 * Later on these will be used when the user switches a provider.
1851 */
1852 private void maybeSaveSettingsForVoicemailProvider(String key,
Andrew Leeb490d732014-10-27 15:00:41 -07001853 VoicemailProviderSettings newSettings) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001854 if (mVoicemailProviders == null) {
1855 return;
1856 }
Andrew Leeb490d732014-10-27 15:00:41 -07001857 final VoicemailProviderSettings curSettings = loadSettingsForVoiceMailProvider(key);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001858 if (newSettings.equals(curSettings)) {
1859 if (DBG) {
1860 log("maybeSaveSettingsForVoicemailProvider:"
1861 + " Not saving setting for " + key + " since they have not changed");
1862 }
1863 return;
1864 }
1865 if (DBG) log("Saving settings for " + key + ": " + newSettings.toString());
1866 Editor editor = mPerProviderSavedVMNumbers.edit();
Andrew Leeb490d732014-10-27 15:00:41 -07001867 editor.putString(key + VM_NUMBER_TAG, newSettings.getVoicemailNumber());
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001868 String fwdKey = key + FWD_SETTINGS_TAG;
Andrew Leeb490d732014-10-27 15:00:41 -07001869 CallForwardInfo[] s = newSettings.getForwardingSettings();
1870 if (s != VoicemailProviderSettings.NO_FORWARDING) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001871 editor.putInt(fwdKey + FWD_SETTINGS_LENGTH_TAG, s.length);
1872 for (int i = 0; i < s.length; i++) {
1873 final String settingKey = fwdKey + FWD_SETTING_TAG + String.valueOf(i);
1874 final CallForwardInfo fi = s[i];
1875 editor.putInt(settingKey + FWD_SETTING_STATUS, fi.status);
1876 editor.putInt(settingKey + FWD_SETTING_REASON, fi.reason);
1877 editor.putString(settingKey + FWD_SETTING_NUMBER, fi.number);
1878 editor.putInt(settingKey + FWD_SETTING_TIME, fi.timeSeconds);
1879 }
1880 } else {
1881 editor.putInt(fwdKey + FWD_SETTINGS_LENGTH_TAG, 0);
1882 }
1883 editor.apply();
1884 }
1885
1886 /**
1887 * Returns settings previously stored for the currently selected
1888 * voice mail provider. If none is stored returns null.
1889 * If the user switches to a voice mail provider and we have settings
1890 * stored for it we will automatically change the phone's voice mail number
1891 * and forwarding number to the stored one. Otherwise we will bring up provider's configuration
1892 * UI.
1893 */
Andrew Leeb490d732014-10-27 15:00:41 -07001894 private VoicemailProviderSettings loadSettingsForVoiceMailProvider(String key) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001895 final String vmNumberSetting = mPerProviderSavedVMNumbers.getString(key + VM_NUMBER_TAG,
1896 null);
1897 if (vmNumberSetting == null) {
1898 Log.w(LOG_TAG, "VoiceMailProvider settings for the key \"" + key + "\""
1899 + " was not found. Returning null.");
1900 return null;
1901 }
1902
Andrew Leeb490d732014-10-27 15:00:41 -07001903 CallForwardInfo[] cfi = VoicemailProviderSettings.NO_FORWARDING;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001904 String fwdKey = key + FWD_SETTINGS_TAG;
1905 final int fwdLen = mPerProviderSavedVMNumbers.getInt(fwdKey + FWD_SETTINGS_LENGTH_TAG, 0);
1906 if (fwdLen > 0) {
1907 cfi = new CallForwardInfo[fwdLen];
1908 for (int i = 0; i < cfi.length; i++) {
1909 final String settingKey = fwdKey + FWD_SETTING_TAG + String.valueOf(i);
1910 cfi[i] = new CallForwardInfo();
1911 cfi[i].status = mPerProviderSavedVMNumbers.getInt(
1912 settingKey + FWD_SETTING_STATUS, 0);
1913 cfi[i].reason = mPerProviderSavedVMNumbers.getInt(
1914 settingKey + FWD_SETTING_REASON,
1915 CommandsInterface.CF_REASON_ALL_CONDITIONAL);
1916 cfi[i].serviceClass = CommandsInterface.SERVICE_CLASS_VOICE;
1917 cfi[i].toa = PhoneNumberUtils.TOA_International;
1918 cfi[i].number = mPerProviderSavedVMNumbers.getString(
1919 settingKey + FWD_SETTING_NUMBER, "");
1920 cfi[i].timeSeconds = mPerProviderSavedVMNumbers.getInt(
1921 settingKey + FWD_SETTING_TIME, 20);
1922 }
1923 }
1924
Andrew Leeb490d732014-10-27 15:00:41 -07001925 VoicemailProviderSettings settings = new VoicemailProviderSettings(vmNumberSetting, cfi);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001926 if (DBG) log("Loaded settings for " + key + ": " + settings.toString());
1927 return settings;
1928 }
1929
1930 /**
1931 * Deletes settings for the specified provider.
1932 */
1933 private void deleteSettingsForVoicemailProvider(String key) {
1934 if (DBG) log("Deleting settings for" + key);
1935 if (mVoicemailProviders == null) {
1936 return;
1937 }
1938 mPerProviderSavedVMNumbers.edit()
1939 .putString(key + VM_NUMBER_TAG, null)
1940 .putInt(key + FWD_SETTINGS_TAG + FWD_SETTINGS_LENGTH_TAG, 0)
1941 .commit();
1942 }
1943
1944 private String getCurrentVoicemailProviderKey() {
1945 final String key = mVoicemailProviders.getValue();
1946 return (key != null) ? key : DEFAULT_VM_PROVIDER_KEY;
1947 }
1948
1949 @Override
1950 public boolean onOptionsItemSelected(MenuItem item) {
1951 final int itemId = item.getItemId();
1952 if (itemId == android.R.id.home) { // See ActionBar#setDisplayHomeAsUpEnabled()
Yorke Leef2d0cac2013-09-09 19:42:56 -07001953 onBackPressed();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001954 return true;
1955 }
1956 return super.onOptionsItemSelected(item);
1957 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001958 /**
1959 * Finish current Activity and go up to the top level Settings ({@link CallFeaturesSetting}).
1960 * This is useful for implementing "HomeAsUp" capability for second-level Settings.
1961 */
1962 public static void goUpToTopLevelSetting(Activity activity) {
1963 Intent intent = new Intent(activity, CallFeaturesSetting.class);
1964 intent.setAction(Intent.ACTION_MAIN);
1965 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
1966 activity.startActivity(intent);
1967 activity.finish();
1968 }
1969}