blob: eb211f1493484f414f40ef90b6590bebd27ce09e [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;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070036import android.os.AsyncResult;
37import android.os.Bundle;
38import android.os.Handler;
39import android.os.Message;
40import android.os.UserHandle;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070041import android.preference.CheckBoxPreference;
42import android.preference.ListPreference;
43import android.preference.Preference;
44import android.preference.PreferenceActivity;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070045import android.preference.PreferenceManager;
46import android.preference.PreferenceScreen;
47import android.provider.ContactsContract.CommonDataKinds;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070048import android.provider.Settings;
Tyler Gunn4d45d1c2014-09-12 22:17:53 -070049import android.telecom.PhoneAccountHandle;
50import android.telecom.TelecomManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070051import android.telephony.PhoneNumberUtils;
Andrew Lee93c345f2014-10-27 15:25:07 -070052import android.telephony.TelephonyManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070053import android.text.TextUtils;
54import android.util.Log;
55import android.view.MenuItem;
56import android.view.WindowManager;
57import android.widget.ListAdapter;
58
Andrew Lee312e8172014-10-23 17:01:36 -070059import com.android.ims.ImsManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070060import 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 /** Event for Async voicemail change call */
195 private static final int EVENT_VOICEMAIL_CHANGED = 500;
196 private static final int EVENT_FORWARDING_CHANGED = 501;
197 private static final int EVENT_FORWARDING_GET_COMPLETED = 502;
198
Andrew Lee2170a972014-08-13 18:13:01 -0700199 private static final int MSG_UPDATE_VOICEMAIL_RINGTONE_SUMMARY = 1;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700200
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700201 public static final String HAC_KEY = "HACSetting";
202 public static final String HAC_VAL_ON = "ON";
203 public static final String HAC_VAL_OFF = "OFF";
204
205 /** Handle to voicemail pref */
206 private static final int VOICEMAIL_PREF_ID = 1;
207 private static final int VOICEMAIL_PROVIDER_CFG_ID = 2;
208
209 private Phone mPhone;
210
211 private AudioManager mAudioManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700212
213 private static final int VM_NOCHANGE_ERROR = 400;
214 private static final int VM_RESPONSE_ERROR = 500;
215 private static final int FW_SET_RESPONSE_ERROR = 501;
216 private static final int FW_GET_RESPONSE_ERROR = 502;
217
218
219 // dialog identifiers for voicemail
220 private static final int VOICEMAIL_DIALOG_CONFIRM = 600;
221 private static final int VOICEMAIL_FWD_SAVING_DIALOG = 601;
222 private static final int VOICEMAIL_FWD_READING_DIALOG = 602;
223 private static final int VOICEMAIL_REVERTING_DIALOG = 603;
224
225 // status message sent back from handlers
226 private static final int MSG_OK = 100;
227
228 // special statuses for voicemail controls.
229 private static final int MSG_VM_EXCEPTION = 400;
230 private static final int MSG_FW_SET_EXCEPTION = 401;
231 private static final int MSG_FW_GET_EXCEPTION = 402;
232 private static final int MSG_VM_OK = 600;
233 private static final int MSG_VM_NOCHANGE = 700;
234
Andrew Leee438b312014-10-29 16:59:15 -0700235 /**
236 * @see CallForwardInfo#status
237 */
238 private static final int CALL_FORWARD_INFO_INACTIVE_STATUS = 0;
239
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700240 // voicemail notification vibration string constants
241 private static final String VOICEMAIL_VIBRATION_ALWAYS = "always";
242 private static final String VOICEMAIL_VIBRATION_NEVER = "never";
243
244 private EditPhoneNumberPreference mSubMenuVoicemailSettings;
245
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700246 /** Whether dialpad plays DTMF tone or not. */
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700247 private CheckBoxPreference mButtonAutoRetry;
248 private CheckBoxPreference mButtonHAC;
249 private ListPreference mButtonDTMF;
250 private ListPreference mButtonTTY;
Andrew Leece8ae2a2014-09-10 10:41:48 -0700251 private Preference mPhoneAccountSettingsPreference;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700252 private ListPreference mVoicemailProviders;
Andrew Lee97708a42014-09-25 12:39:07 -0700253 private PreferenceScreen mVoicemailSettingsScreen;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700254 private PreferenceScreen mVoicemailSettings;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700255 private CheckBoxPreference mVoicemailNotificationVibrate;
Andrew Leedf14ead2014-10-17 14:22:52 -0700256 private CheckBoxPreference mEnableVideoCalling;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700257
258 private class VoiceMailProvider {
259 public VoiceMailProvider(String name, Intent intent) {
260 this.name = name;
261 this.intent = intent;
262 }
263 public String name;
264 public Intent intent;
265 }
266
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700267 private SharedPreferences mPerProviderSavedVMNumbers;
268
269 /**
270 * Results of reading forwarding settings
271 */
272 private CallForwardInfo[] mForwardingReadResults = null;
273
274 /**
275 * Result of forwarding number change.
276 * Keys are reasons (eg. unconditional forwarding).
277 */
278 private Map<Integer, AsyncResult> mForwardingChangeResults = null;
279
280 /**
281 * Expected CF read result types.
282 * This set keeps track of the CF types for which we've issued change
283 * commands so we can tell when we've received all of the responses.
284 */
285 private Collection<Integer> mExpectedChangeResultReasons = null;
286
287 /**
288 * Result of vm number change
289 */
290 private AsyncResult mVoicemailChangeResult = null;
291
292 /**
293 * Previous VM provider setting so we can return to it in case of failure.
294 */
295 private String mPreviousVMProviderKey = null;
296
297 /**
298 * Id of the dialog being currently shown.
299 */
300 private int mCurrentDialogId = 0;
301
302 /**
303 * Flag indicating that we are invoking settings for the voicemail provider programmatically
304 * due to vm provider change.
305 */
306 private boolean mVMProviderSettingsForced = false;
307
308 /**
309 * Flag indicating that we are making changes to vm or fwd numbers
310 * due to vm provider change.
311 */
312 private boolean mChangingVMorFwdDueToProviderChange = false;
313
314 /**
315 * True if we are in the process of vm & fwd number change and vm has already been changed.
316 * This is used to decide what to do in case of rollback.
317 */
318 private boolean mVMChangeCompletedSuccessfully = false;
319
320 /**
321 * True if we had full or partial failure setting forwarding numbers and so need to roll them
322 * back.
323 */
324 private boolean mFwdChangesRequireRollback = false;
325
326 /**
327 * Id of error msg to display to user once we are done reverting the VM provider to the previous
328 * one.
329 */
330 private int mVMOrFwdSetError = 0;
331
332 /**
333 * Data about discovered voice mail settings providers.
334 * Is populated by querying which activities can handle ACTION_CONFIGURE_VOICEMAIL.
335 * They key in this map is package name + activity name.
336 * We always add an entry for the default provider with a key of empty
337 * string and intent value of null.
338 * @see #initVoiceMailProviders()
339 */
340 private final Map<String, VoiceMailProvider> mVMProvidersData =
341 new HashMap<String, VoiceMailProvider>();
342
343 /** string to hold old voicemail number as it is being updated. */
344 private String mOldVmNumber;
345
346 // New call forwarding settings and vm number we will be setting
347 // Need to save these since before we get to saving we need to asynchronously
348 // query the existing forwarding settings.
349 private CallForwardInfo[] mNewFwdSettings;
350 private String mNewVMNumber;
351
352 private boolean mForeground;
353
354 @Override
355 public void onPause() {
356 super.onPause();
357 mForeground = false;
358 }
359
360 /**
361 * We have to pull current settings from the network for all kinds of
362 * voicemail providers so we can tell whether we have to update them,
363 * so use this bit to keep track of whether we're reading settings for the
364 * default provider and should therefore save them out when done.
365 */
366 private boolean mReadingSettingsForDefaultProvider = false;
367
Tyler Gunnbaee2952014-09-10 16:01:02 -0700368 /**
369 * Used to indicate that the voicemail preference should be shown.
370 */
371 private boolean mShowVoicemailPreference = false;
372
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700373 /*
374 * Click Listeners, handle click based on objects attached to UI.
375 */
376
377 // Click listener for all toggle events
378 @Override
379 public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
380 if (preference == mSubMenuVoicemailSettings) {
381 return true;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700382 } else if (preference == mButtonDTMF) {
383 return true;
384 } else if (preference == mButtonTTY) {
385 return true;
386 } else if (preference == mButtonAutoRetry) {
387 android.provider.Settings.Global.putInt(mPhone.getContext().getContentResolver(),
388 android.provider.Settings.Global.CALL_AUTO_RETRY,
389 mButtonAutoRetry.isChecked() ? 1 : 0);
390 return true;
391 } else if (preference == mButtonHAC) {
392 int hac = mButtonHAC.isChecked() ? 1 : 0;
393 // Update HAC value in Settings database
394 Settings.System.putInt(mPhone.getContext().getContentResolver(),
395 Settings.System.HEARING_AID, hac);
396
397 // Update HAC Value in AudioManager
398 mAudioManager.setParameter(HAC_KEY, hac != 0 ? HAC_VAL_ON : HAC_VAL_OFF);
399 return true;
400 } else if (preference == mVoicemailSettings) {
Yorke Leea0f63bf2014-10-09 18:27:20 -0700401 final Dialog dialog = mVoicemailSettings.getDialog();
402 if (dialog != null) {
403 dialog.getActionBar().setDisplayHomeAsUpEnabled(false);
404 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700405 if (DBG) log("onPreferenceTreeClick: Voicemail Settings Preference is clicked.");
406 if (preference.getIntent() != null) {
407 if (DBG) {
408 log("onPreferenceTreeClick: Invoking cfg intent "
409 + preference.getIntent().getPackage());
410 }
411
412 // onActivityResult() will be responsible for resetting some of variables.
413 this.startActivityForResult(preference.getIntent(), VOICEMAIL_PROVIDER_CFG_ID);
414 return true;
415 } else {
416 if (DBG) {
417 log("onPreferenceTreeClick:"
418 + " No Intent is available. Use default behavior defined in xml.");
419 }
420
421 // There's no onActivityResult(), so we need to take care of some of variables
422 // which should be reset here.
423 mPreviousVMProviderKey = DEFAULT_VM_PROVIDER_KEY;
424 mVMProviderSettingsForced = false;
425
426 // This should let the preference use default behavior in the xml.
427 return false;
428 }
Andrew Lee97708a42014-09-25 12:39:07 -0700429 } else if (preference == mVoicemailSettingsScreen) {
Yorke Leea0f63bf2014-10-09 18:27:20 -0700430 final Dialog dialog = mVoicemailSettingsScreen.getDialog();
431 if (dialog != null) {
432 dialog.getActionBar().setDisplayHomeAsUpEnabled(false);
433 }
Andrew Lee97708a42014-09-25 12:39:07 -0700434 return false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700435 }
436 return false;
437 }
438
439 /**
440 * Implemented to support onPreferenceChangeListener to look for preference
441 * changes.
442 *
443 * @param preference is the preference to be changed
444 * @param objValue should be the value of the selection, NOT its localized
445 * display value.
446 */
447 @Override
448 public boolean onPreferenceChange(Preference preference, Object objValue) {
449 if (DBG) {
Andrew Leedf14ead2014-10-17 14:22:52 -0700450 log("onPreferenceChange(). preference: \"" + preference + "\""
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700451 + ", value: \"" + objValue + "\"");
452 }
Andrew Lee2170a972014-08-13 18:13:01 -0700453
454 if (preference == mButtonDTMF) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700455 int index = mButtonDTMF.findIndexOfValue((String) objValue);
456 Settings.System.putInt(mPhone.getContext().getContentResolver(),
457 Settings.System.DTMF_TONE_TYPE_WHEN_DIALING, index);
458 } else if (preference == mButtonTTY) {
459 handleTTYChange(preference, objValue);
460 } else if (preference == mVoicemailProviders) {
461 final String newProviderKey = (String) objValue;
462 if (DBG) {
463 log("Voicemail Provider changes from \"" + mPreviousVMProviderKey
464 + "\" to \"" + newProviderKey + "\".");
465 }
466 // If previous provider key and the new one is same, we don't need to handle it.
467 if (mPreviousVMProviderKey.equals(newProviderKey)) {
468 if (DBG) log("No change is made toward VM provider setting.");
469 return true;
470 }
471 updateVMPreferenceWidgets(newProviderKey);
472
Andrew Leeb490d732014-10-27 15:00:41 -0700473 final VoicemailProviderSettings newProviderSettings =
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700474 loadSettingsForVoiceMailProvider(newProviderKey);
475
476 // If the user switches to a voice mail provider and we have a
477 // numbers stored for it we will automatically change the
478 // phone's
479 // voice mail and forwarding number to the stored ones.
480 // Otherwise we will bring up provider's configuration UI.
481
482 if (newProviderSettings == null) {
483 // Force the user into a configuration of the chosen provider
484 Log.w(LOG_TAG, "Saved preferences not found - invoking config");
485 mVMProviderSettingsForced = true;
486 simulatePreferenceClick(mVoicemailSettings);
487 } else {
488 if (DBG) log("Saved preferences found - switching to them");
489 // Set this flag so if we get a failure we revert to previous provider
490 mChangingVMorFwdDueToProviderChange = true;
491 saveVoiceMailAndForwardingNumber(newProviderKey, newProviderSettings);
492 }
Andrew Leedf14ead2014-10-17 14:22:52 -0700493 } else if (preference == mEnableVideoCalling) {
Andrew Lee312e8172014-10-23 17:01:36 -0700494 if (ImsManager.isEnhanced4gLteModeSettingEnabledByUser(mPhone.getContext())) {
495 PhoneGlobals.getInstance().phoneMgr.enableVideoCalling((boolean) objValue);
496 } else {
497 AlertDialog.Builder builder = new AlertDialog.Builder(this);
498 DialogInterface.OnClickListener networkSettingsClickListener =
499 new Dialog.OnClickListener() {
500 @Override
501 public void onClick(DialogInterface dialog, int which) {
502 startActivity(new Intent(mPhone.getContext(),
503 com.android.phone.MobileNetworkSettings.class));
504 }
505 };
506 builder.setMessage(getResources().getString(
507 R.string.enable_video_calling_dialog_msg))
508 .setNeutralButton(getResources().getString(
509 R.string.enable_video_calling_dialog_settings),
510 networkSettingsClickListener)
511 .setPositiveButton(android.R.string.ok, null)
512 .show();
513 return false;
514 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700515 }
516 // always let the preference setting proceed.
517 return true;
518 }
519
520 @Override
521 public void onDialogClosed(EditPhoneNumberPreference preference, int buttonClicked) {
522 if (DBG) log("onPreferenceClick: request preference click on dialog close: " +
523 buttonClicked);
524 if (buttonClicked == DialogInterface.BUTTON_NEGATIVE) {
525 return;
526 }
527
528 if (preference == mSubMenuVoicemailSettings) {
Andrew Leee438b312014-10-29 16:59:15 -0700529 VoicemailProviderSettings newSettings = new VoicemailProviderSettings(
530 mSubMenuVoicemailSettings.getPhoneNumber(),
531 VoicemailProviderSettings.NO_FORWARDING);
532 saveVoiceMailAndForwardingNumber(getCurrentVoicemailProviderKey(), newSettings);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700533 }
534 }
535
536 /**
537 * Implemented for EditPhoneNumberPreference.GetDefaultNumberListener.
538 * This method set the default values for the various
539 * EditPhoneNumberPreference dialogs.
540 */
541 @Override
542 public String onGetDefaultNumber(EditPhoneNumberPreference preference) {
543 if (preference == mSubMenuVoicemailSettings) {
544 // update the voicemail number field, which takes care of the
545 // mSubMenuVoicemailSettings itself, so we should return null.
546 if (DBG) log("updating default for voicemail dialog");
547 updateVoiceNumberField();
548 return null;
549 }
550
551 String vmDisplay = mPhone.getVoiceMailNumber();
552 if (TextUtils.isEmpty(vmDisplay)) {
553 // if there is no voicemail number, we just return null to
554 // indicate no contribution.
555 return null;
556 }
557
558 // Return the voicemail number prepended with "VM: "
559 if (DBG) log("updating default for call forwarding dialogs");
560 return getString(R.string.voicemail_abbreviated) + " " + vmDisplay;
561 }
562
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700563 private void switchToPreviousVoicemailProvider() {
564 if (DBG) log("switchToPreviousVoicemailProvider " + mPreviousVMProviderKey);
565 if (mPreviousVMProviderKey != null) {
566 if (mVMChangeCompletedSuccessfully || mFwdChangesRequireRollback) {
567 // we have to revert with carrier
568 if (DBG) {
569 log("Needs to rollback."
570 + " mVMChangeCompletedSuccessfully=" + mVMChangeCompletedSuccessfully
571 + ", mFwdChangesRequireRollback=" + mFwdChangesRequireRollback);
572 }
573
574 showDialogIfForeground(VOICEMAIL_REVERTING_DIALOG);
Andrew Leeb490d732014-10-27 15:00:41 -0700575 final VoicemailProviderSettings prevSettings =
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700576 loadSettingsForVoiceMailProvider(mPreviousVMProviderKey);
577 if (prevSettings == null) {
578 // prevSettings never becomes null since it should be already loaded!
Andrew Leeb490d732014-10-27 15:00:41 -0700579 Log.e(LOG_TAG, "VoicemailProviderSettings for the key \""
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700580 + mPreviousVMProviderKey + "\" becomes null, which is unexpected.");
581 if (DBG) {
582 Log.e(LOG_TAG,
583 "mVMChangeCompletedSuccessfully: " + mVMChangeCompletedSuccessfully
584 + ", mFwdChangesRequireRollback: " + mFwdChangesRequireRollback);
585 }
586 }
587 if (mVMChangeCompletedSuccessfully) {
Andrew Leeb490d732014-10-27 15:00:41 -0700588 mNewVMNumber = prevSettings.getVoicemailNumber();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700589 Log.i(LOG_TAG, "VM change is already completed successfully."
590 + "Have to revert VM back to " + mNewVMNumber + " again.");
591 mPhone.setVoiceMailNumber(
592 mPhone.getVoiceMailAlphaTag().toString(),
593 mNewVMNumber,
594 Message.obtain(mRevertOptionComplete, EVENT_VOICEMAIL_CHANGED));
595 }
596 if (mFwdChangesRequireRollback) {
597 Log.i(LOG_TAG, "Requested to rollback Fwd changes.");
Andrew Leeb490d732014-10-27 15:00:41 -0700598 final CallForwardInfo[] prevFwdSettings = prevSettings.getForwardingSettings();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700599 if (prevFwdSettings != null) {
600 Map<Integer, AsyncResult> results =
601 mForwardingChangeResults;
602 resetForwardingChangeState();
603 for (int i = 0; i < prevFwdSettings.length; i++) {
604 CallForwardInfo fi = prevFwdSettings[i];
605 if (DBG) log("Reverting fwd #: " + i + ": " + fi.toString());
606 // Only revert the settings for which the update
607 // succeeded
608 AsyncResult result = results.get(fi.reason);
609 if (result != null && result.exception == null) {
610 mExpectedChangeResultReasons.add(fi.reason);
611 mPhone.setCallForwardingOption(
612 (fi.status == 1 ?
613 CommandsInterface.CF_ACTION_REGISTRATION :
614 CommandsInterface.CF_ACTION_DISABLE),
615 fi.reason,
616 fi.number,
617 fi.timeSeconds,
618 mRevertOptionComplete.obtainMessage(
619 EVENT_FORWARDING_CHANGED, i, 0));
620 }
621 }
622 }
623 }
624 } else {
625 if (DBG) log("No need to revert");
626 onRevertDone();
627 }
628 }
629 }
630
631 private void onRevertDone() {
632 if (DBG) log("Flipping provider key back to " + mPreviousVMProviderKey);
633 mVoicemailProviders.setValue(mPreviousVMProviderKey);
634 updateVMPreferenceWidgets(mPreviousVMProviderKey);
635 updateVoiceNumberField();
636 if (mVMOrFwdSetError != 0) {
637 showVMDialog(mVMOrFwdSetError);
638 mVMOrFwdSetError = 0;
639 }
640 }
641
642 @Override
643 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
644 if (DBG) {
645 log("onActivityResult: requestCode: " + requestCode
646 + ", resultCode: " + resultCode
647 + ", data: " + data);
648 }
649 // there are cases where the contact picker may end up sending us more than one
650 // request. We want to ignore the request if we're not in the correct state.
651 if (requestCode == VOICEMAIL_PROVIDER_CFG_ID) {
652 boolean failure = false;
653
654 // No matter how the processing of result goes lets clear the flag
655 if (DBG) log("mVMProviderSettingsForced: " + mVMProviderSettingsForced);
656 final boolean isVMProviderSettingsForced = mVMProviderSettingsForced;
657 mVMProviderSettingsForced = false;
658
659 String vmNum = null;
660 if (resultCode != RESULT_OK) {
661 if (DBG) log("onActivityResult: vm provider cfg result not OK.");
662 failure = true;
663 } else {
664 if (data == null) {
665 if (DBG) log("onActivityResult: vm provider cfg result has no data");
666 failure = true;
667 } else {
668 if (data.getBooleanExtra(SIGNOUT_EXTRA, false)) {
669 if (DBG) log("Provider requested signout");
670 if (isVMProviderSettingsForced) {
671 if (DBG) log("Going back to previous provider on signout");
672 switchToPreviousVoicemailProvider();
673 } else {
674 final String victim = getCurrentVoicemailProviderKey();
675 if (DBG) log("Relaunching activity and ignoring " + victim);
676 Intent i = new Intent(ACTION_ADD_VOICEMAIL);
677 i.putExtra(IGNORE_PROVIDER_EXTRA, victim);
678 i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
679 this.startActivity(i);
680 }
681 return;
682 }
683 vmNum = data.getStringExtra(VM_NUMBER_EXTRA);
684 if (vmNum == null || vmNum.length() == 0) {
685 if (DBG) log("onActivityResult: vm provider cfg result has no vmnum");
686 failure = true;
687 }
688 }
689 }
690 if (failure) {
691 if (DBG) log("Failure in return from voicemail provider");
692 if (isVMProviderSettingsForced) {
693 switchToPreviousVoicemailProvider();
694 } else {
695 if (DBG) log("Not switching back the provider since this is not forced config");
696 }
697 return;
698 }
699 mChangingVMorFwdDueToProviderChange = isVMProviderSettingsForced;
700 final String fwdNum = data.getStringExtra(FWD_NUMBER_EXTRA);
701
Santos Cordonda120f42014-08-06 04:44:34 -0700702 // TODO: It would be nice to load the current network setting for this and
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700703 // send it to the provider when it's config is invoked so it can use this as default
704 final int fwdNumTime = data.getIntExtra(FWD_NUMBER_TIME_EXTRA, 20);
705
706 if (DBG) log("onActivityResult: vm provider cfg result " +
707 (fwdNum != null ? "has" : " does not have") + " forwarding number");
708 saveVoiceMailAndForwardingNumber(getCurrentVoicemailProviderKey(),
Andrew Leeb490d732014-10-27 15:00:41 -0700709 new VoicemailProviderSettings(vmNum, fwdNum, fwdNumTime));
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700710 return;
711 }
712
713 if (requestCode == VOICEMAIL_PREF_ID) {
714 if (resultCode != RESULT_OK) {
715 if (DBG) log("onActivityResult: contact picker result not OK.");
716 return;
717 }
718
719 Cursor cursor = null;
720 try {
721 cursor = getContentResolver().query(data.getData(),
722 NUM_PROJECTION, null, null, null);
723 if ((cursor == null) || (!cursor.moveToFirst())) {
724 if (DBG) log("onActivityResult: bad contact data, no results found.");
725 return;
726 }
727 mSubMenuVoicemailSettings.onPickActivityResult(cursor.getString(0));
728 return;
729 } finally {
730 if (cursor != null) {
731 cursor.close();
732 }
733 }
734 }
735
736 super.onActivityResult(requestCode, resultCode, data);
737 }
738
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700739 /**
740 * Wrapper around showDialog() that will silently do nothing if we're
741 * not in the foreground.
742 *
743 * This is useful here because most of the dialogs we display from
744 * this class are triggered by asynchronous events (like
745 * success/failure messages from the telephony layer) and it's
746 * possible for those events to come in even after the user has gone
747 * to a different screen.
748 */
749 // TODO: this is too brittle: it's still easy to accidentally add new
750 // code here that calls showDialog() directly (which will result in a
751 // WindowManager$BadTokenException if called after the activity has
752 // been stopped.)
753 //
754 // It would be cleaner to do the "if (mForeground)" check in one
755 // central place, maybe by using a single Handler for all asynchronous
756 // events (and have *that* discard events if we're not in the
757 // foreground.)
758 //
759 // Unfortunately it's not that simple, since we sometimes need to do
760 // actual work to handle these events whether or not we're in the
761 // foreground (see the Handler code in mSetOptionComplete for
762 // example.)
763 private void showDialogIfForeground(int id) {
764 if (mForeground) {
765 showDialog(id);
766 }
767 }
768
769 private void dismissDialogSafely(int id) {
770 try {
771 dismissDialog(id);
772 } catch (IllegalArgumentException e) {
773 // This is expected in the case where we were in the background
774 // at the time we would normally have shown the dialog, so we didn't
775 // show it.
776 }
777 }
778
Andrew Leeb490d732014-10-27 15:00:41 -0700779 private void saveVoiceMailAndForwardingNumber(
780 String key, VoicemailProviderSettings newSettings) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700781 if (DBG) log("saveVoiceMailAndForwardingNumber: " + newSettings.toString());
Andrew Leeb490d732014-10-27 15:00:41 -0700782 mNewVMNumber = newSettings.getVoicemailNumber();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700783 // empty vm number == clearing the vm number ?
784 if (mNewVMNumber == null) {
785 mNewVMNumber = "";
786 }
787
Andrew Leeb490d732014-10-27 15:00:41 -0700788 mNewFwdSettings = newSettings.getForwardingSettings();
789 if (DBG) log("newFwdNumber "
790 + String.valueOf((mNewFwdSettings != null ? mNewFwdSettings.length : 0))
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700791 + " settings");
792
793 // No fwd settings on CDMA
794 if (mPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
795 if (DBG) log("ignoring forwarding setting since this is CDMA phone");
Andrew Leeb490d732014-10-27 15:00:41 -0700796 mNewFwdSettings = VoicemailProviderSettings.NO_FORWARDING;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700797 }
798
Andrew Leee3c15212014-10-28 13:12:55 -0700799 // Throw a warning if the voicemail is the same and we did not change forwarding.
Andrew Leeb490d732014-10-27 15:00:41 -0700800 if (mNewVMNumber.equals(mOldVmNumber)
801 && mNewFwdSettings == VoicemailProviderSettings.NO_FORWARDING) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700802 showVMDialog(MSG_VM_NOCHANGE);
803 return;
804 }
805
806 maybeSaveSettingsForVoicemailProvider(key, newSettings);
807 mVMChangeCompletedSuccessfully = false;
808 mFwdChangesRequireRollback = false;
809 mVMOrFwdSetError = 0;
810 if (!key.equals(mPreviousVMProviderKey)) {
811 mReadingSettingsForDefaultProvider =
812 mPreviousVMProviderKey.equals(DEFAULT_VM_PROVIDER_KEY);
813 if (DBG) log("Reading current forwarding settings");
Andrew Leeb490d732014-10-27 15:00:41 -0700814 int numSettingsReasons = VoicemailProviderSettings.FORWARDING_SETTINGS_REASONS.length;
815 mForwardingReadResults = new CallForwardInfo[numSettingsReasons];
816 for (int i = 0; i < mForwardingReadResults.length; i++) {
817 mPhone.getCallForwardingOption(
818 VoicemailProviderSettings.FORWARDING_SETTINGS_REASONS[i],
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700819 mGetOptionComplete.obtainMessage(EVENT_FORWARDING_GET_COMPLETED, i, 0));
820 }
821 showDialogIfForeground(VOICEMAIL_FWD_READING_DIALOG);
822 } else {
823 saveVoiceMailAndForwardingNumberStage2();
824 }
825 }
826
827 private final Handler mGetOptionComplete = new Handler() {
828 @Override
829 public void handleMessage(Message msg) {
830 AsyncResult result = (AsyncResult) msg.obj;
831 switch (msg.what) {
832 case EVENT_FORWARDING_GET_COMPLETED:
833 handleForwardingSettingsReadResult(result, msg.arg1);
834 break;
835 }
836 }
837 };
838
839 private void handleForwardingSettingsReadResult(AsyncResult ar, int idx) {
840 if (DBG) Log.d(LOG_TAG, "handleForwardingSettingsReadResult: " + idx);
841 Throwable error = null;
842 if (ar.exception != null) {
843 if (DBG) Log.d(LOG_TAG, "FwdRead: ar.exception=" +
844 ar.exception.getMessage());
845 error = ar.exception;
846 }
847 if (ar.userObj instanceof Throwable) {
848 if (DBG) Log.d(LOG_TAG, "FwdRead: userObj=" +
849 ((Throwable)ar.userObj).getMessage());
850 error = (Throwable)ar.userObj;
851 }
852
853 // We may have already gotten an error and decided to ignore the other results.
854 if (mForwardingReadResults == null) {
855 if (DBG) Log.d(LOG_TAG, "ignoring fwd reading result: " + idx);
856 return;
857 }
858
859 // In case of error ignore other results, show an error dialog
860 if (error != null) {
861 if (DBG) Log.d(LOG_TAG, "Error discovered for fwd read : " + idx);
862 mForwardingReadResults = null;
863 dismissDialogSafely(VOICEMAIL_FWD_READING_DIALOG);
864 showVMDialog(MSG_FW_GET_EXCEPTION);
865 return;
866 }
867
868 // Get the forwarding info
869 final CallForwardInfo cfInfoArray[] = (CallForwardInfo[]) ar.result;
870 CallForwardInfo fi = null;
871 for (int i = 0 ; i < cfInfoArray.length; i++) {
872 if ((cfInfoArray[i].serviceClass & CommandsInterface.SERVICE_CLASS_VOICE) != 0) {
873 fi = cfInfoArray[i];
874 break;
875 }
876 }
877 if (fi == null) {
878
879 // In case we go nothing it means we need this reason disabled
880 // so create a CallForwardInfo for capturing this
881 if (DBG) Log.d(LOG_TAG, "Creating default info for " + idx);
882 fi = new CallForwardInfo();
883 fi.status = 0;
Andrew Leeb490d732014-10-27 15:00:41 -0700884 fi.reason = VoicemailProviderSettings.FORWARDING_SETTINGS_REASONS[idx];
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700885 fi.serviceClass = CommandsInterface.SERVICE_CLASS_VOICE;
886 } else {
887 // if there is not a forwarding number, ensure the entry is set to "not active."
888 if (fi.number == null || fi.number.length() == 0) {
889 fi.status = 0;
890 }
891
892 if (DBG) Log.d(LOG_TAG, "Got " + fi.toString() + " for " + idx);
893 }
894 mForwardingReadResults[idx] = fi;
895
896 // Check if we got all the results already
897 boolean done = true;
898 for (int i = 0; i < mForwardingReadResults.length; i++) {
899 if (mForwardingReadResults[i] == null) {
900 done = false;
901 break;
902 }
903 }
904 if (done) {
905 if (DBG) Log.d(LOG_TAG, "Done receiving fwd info");
906 dismissDialogSafely(VOICEMAIL_FWD_READING_DIALOG);
907 if (mReadingSettingsForDefaultProvider) {
908 maybeSaveSettingsForVoicemailProvider(DEFAULT_VM_PROVIDER_KEY,
Andrew Leeb490d732014-10-27 15:00:41 -0700909 new VoicemailProviderSettings(this.mOldVmNumber,
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700910 mForwardingReadResults));
911 mReadingSettingsForDefaultProvider = false;
912 }
913 saveVoiceMailAndForwardingNumberStage2();
914 } else {
915 if (DBG) Log.d(LOG_TAG, "Not done receiving fwd info");
916 }
917 }
918
919 private CallForwardInfo infoForReason(CallForwardInfo[] infos, int reason) {
920 CallForwardInfo result = null;
921 if (null != infos) {
922 for (CallForwardInfo info : infos) {
923 if (info.reason == reason) {
924 result = info;
925 break;
926 }
927 }
928 }
929 return result;
930 }
931
Andrew Leee438b312014-10-29 16:59:15 -0700932 private boolean isUpdateRequired(CallForwardInfo oldInfo, CallForwardInfo newInfo) {
933 if (oldInfo == null) {
934 return true;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700935 }
Andrew Leee438b312014-10-29 16:59:15 -0700936
937 // If we're disabling a type of forwarding, don't make any change if it's already disabled.
938 if (newInfo.status == CALL_FORWARD_INFO_INACTIVE_STATUS
939 && oldInfo.status == CALL_FORWARD_INFO_INACTIVE_STATUS) {
940 return false;
941 }
942
943 return true;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700944 }
945
946 private void resetForwardingChangeState() {
947 mForwardingChangeResults = new HashMap<Integer, AsyncResult>();
948 mExpectedChangeResultReasons = new HashSet<Integer>();
949 }
950
951 // Called after we are done saving the previous forwarding settings if
952 // we needed.
953 private void saveVoiceMailAndForwardingNumberStage2() {
954 mForwardingChangeResults = null;
955 mVoicemailChangeResult = null;
Andrew Leeb490d732014-10-27 15:00:41 -0700956 if (mNewFwdSettings != VoicemailProviderSettings.NO_FORWARDING) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700957 resetForwardingChangeState();
958 for (int i = 0; i < mNewFwdSettings.length; i++) {
959 CallForwardInfo fi = mNewFwdSettings[i];
960
961 final boolean doUpdate = isUpdateRequired(infoForReason(
962 mForwardingReadResults, fi.reason), fi);
963
964 if (doUpdate) {
965 if (DBG) log("Setting fwd #: " + i + ": " + fi.toString());
966 mExpectedChangeResultReasons.add(i);
967
968 mPhone.setCallForwardingOption(
969 fi.status == 1 ?
970 CommandsInterface.CF_ACTION_REGISTRATION :
971 CommandsInterface.CF_ACTION_DISABLE,
972 fi.reason,
973 fi.number,
974 fi.timeSeconds,
975 mSetOptionComplete.obtainMessage(
976 EVENT_FORWARDING_CHANGED, fi.reason, 0));
977 }
978 }
979 showDialogIfForeground(VOICEMAIL_FWD_SAVING_DIALOG);
980 } else {
981 if (DBG) log("Not touching fwd #");
982 setVMNumberWithCarrier();
983 }
984 }
985
986 private void setVMNumberWithCarrier() {
987 if (DBG) log("save voicemail #: " + mNewVMNumber);
988 mPhone.setVoiceMailNumber(
989 mPhone.getVoiceMailAlphaTag().toString(),
990 mNewVMNumber,
991 Message.obtain(mSetOptionComplete, EVENT_VOICEMAIL_CHANGED));
992 }
993
994 /**
995 * Callback to handle option update completions
996 */
997 private final Handler mSetOptionComplete = new Handler() {
998 @Override
999 public void handleMessage(Message msg) {
1000 AsyncResult result = (AsyncResult) msg.obj;
1001 boolean done = false;
1002 switch (msg.what) {
1003 case EVENT_VOICEMAIL_CHANGED:
1004 mVoicemailChangeResult = result;
Andrew Leee438b312014-10-29 16:59:15 -07001005 mVMChangeCompletedSuccessfully = isVmChangeSuccess();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001006 done = true;
1007 break;
1008 case EVENT_FORWARDING_CHANGED:
1009 mForwardingChangeResults.put(msg.arg1, result);
1010 if (result.exception != null) {
1011 Log.w(LOG_TAG, "Error in setting fwd# " + msg.arg1 + ": " +
1012 result.exception.getMessage());
1013 } else {
1014 if (DBG) log("Success in setting fwd# " + msg.arg1);
1015 }
Andrew Leee438b312014-10-29 16:59:15 -07001016 if (isForwardingCompleted()) {
1017 if (isFwdChangeSuccess()) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001018 if (DBG) log("Overall fwd changes completed ok, starting vm change");
1019 setVMNumberWithCarrier();
1020 } else {
1021 Log.w(LOG_TAG, "Overall fwd changes completed in failure. " +
1022 "Check if we need to try rollback for some settings.");
1023 mFwdChangesRequireRollback = false;
1024 Iterator<Map.Entry<Integer,AsyncResult>> it =
1025 mForwardingChangeResults.entrySet().iterator();
1026 while (it.hasNext()) {
1027 Map.Entry<Integer,AsyncResult> entry = it.next();
1028 if (entry.getValue().exception == null) {
1029 // If at least one succeeded we have to revert
1030 Log.i(LOG_TAG, "Rollback will be required");
1031 mFwdChangesRequireRollback = true;
1032 break;
1033 }
1034 }
1035 if (!mFwdChangesRequireRollback) {
1036 Log.i(LOG_TAG, "No rollback needed.");
1037 }
1038 done = true;
1039 }
1040 }
1041 break;
1042 default:
1043 // TODO: should never reach this, may want to throw exception
1044 }
1045 if (done) {
1046 if (DBG) log("All VM provider related changes done");
1047 if (mForwardingChangeResults != null) {
1048 dismissDialogSafely(VOICEMAIL_FWD_SAVING_DIALOG);
1049 }
Andrew Leee438b312014-10-29 16:59:15 -07001050 handleSetVmOrFwdMessage();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001051 }
1052 }
1053 };
1054
1055 /**
1056 * Callback to handle option revert completions
1057 */
1058 private final Handler mRevertOptionComplete = new Handler() {
1059 @Override
1060 public void handleMessage(Message msg) {
1061 AsyncResult result = (AsyncResult) msg.obj;
1062 switch (msg.what) {
1063 case EVENT_VOICEMAIL_CHANGED:
1064 mVoicemailChangeResult = result;
1065 if (DBG) log("VM revert complete msg");
1066 break;
1067 case EVENT_FORWARDING_CHANGED:
1068 mForwardingChangeResults.put(msg.arg1, result);
1069 if (result.exception != null) {
1070 if (DBG) log("Error in reverting fwd# " + msg.arg1 + ": " +
1071 result.exception.getMessage());
1072 } else {
1073 if (DBG) log("Success in reverting fwd# " + msg.arg1);
1074 }
1075 if (DBG) log("FWD revert complete msg ");
1076 break;
1077 default:
1078 // TODO: should never reach this, may want to throw exception
1079 }
1080 final boolean done =
1081 (!mVMChangeCompletedSuccessfully || mVoicemailChangeResult != null) &&
Andrew Leee438b312014-10-29 16:59:15 -07001082 (!mFwdChangesRequireRollback || isForwardingCompleted());
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001083 if (done) {
1084 if (DBG) log("All VM reverts done");
1085 dismissDialogSafely(VOICEMAIL_REVERTING_DIALOG);
1086 onRevertDone();
1087 }
1088 }
1089 };
1090
1091 /**
Andrew Leee438b312014-10-29 16:59:15 -07001092 * Return true if there is a change result for every reason for which we expect a result.
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001093 */
Andrew Leee438b312014-10-29 16:59:15 -07001094 private boolean isForwardingCompleted() {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001095 if (mForwardingChangeResults == null) {
Andrew Leee438b312014-10-29 16:59:15 -07001096 return true;
1097 }
1098
1099 for (Integer reason : mExpectedChangeResultReasons) {
1100 if (mForwardingChangeResults.get(reason) == null) {
1101 return false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001102 }
1103 }
Andrew Leee438b312014-10-29 16:59:15 -07001104
1105 return true;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001106 }
Andrew Leee438b312014-10-29 16:59:15 -07001107
1108 private boolean isFwdChangeSuccess() {
1109 if (mForwardingChangeResults == null) {
1110 return true;
1111 }
1112
1113 for (AsyncResult result : mForwardingChangeResults.values()) {
1114 Throwable exception = result.exception;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001115 if (exception != null) {
Andrew Leee438b312014-10-29 16:59:15 -07001116 String msg = exception.getMessage();
1117 msg = (msg != null) ? msg : "";
1118 Log.w(LOG_TAG, "Failed to change forwarding setting. Reason: " + msg);
1119 return false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001120 }
1121 }
Andrew Leee438b312014-10-29 16:59:15 -07001122 return true;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001123 }
1124
Andrew Leee438b312014-10-29 16:59:15 -07001125 private boolean isVmChangeSuccess() {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001126 if (mVoicemailChangeResult.exception != null) {
Andrew Leee438b312014-10-29 16:59:15 -07001127 String msg = mVoicemailChangeResult.exception.getMessage();
1128 msg = (msg != null) ? msg : "";
1129 Log.w(LOG_TAG, "Failed to change voicemail. Reason: " + msg);
1130 return false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001131 }
Andrew Leee438b312014-10-29 16:59:15 -07001132
1133 if (DBG) log("VM change completed successfully.");
1134 return true;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001135 }
1136
Andrew Leee438b312014-10-29 16:59:15 -07001137 private void handleSetVmOrFwdMessage() {
1138 if (DBG) log("handleSetVMMessage: set VM request complete");
1139
1140 if (!isFwdChangeSuccess()) {
1141 handleVmOrFwdSetError(MSG_FW_SET_EXCEPTION);
1142 } else if (!isVmChangeSuccess()) {
1143 handleVmOrFwdSetError(MSG_VM_EXCEPTION);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001144 } else {
Andrew Leee438b312014-10-29 16:59:15 -07001145 if (DBG) log("change VM success!");
1146 handleVmAndFwdSetSuccess(MSG_VM_OK);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001147 }
1148 }
1149
1150 /**
1151 * Called when Voicemail Provider or its forwarding settings failed. Rolls back partly made
1152 * changes to those settings and show "failure" dialog.
1153 *
1154 * @param msgId Message ID used for the specific error case. {@link #MSG_FW_SET_EXCEPTION} or
1155 * {@link #MSG_VM_EXCEPTION}
1156 */
Andrew Leee438b312014-10-29 16:59:15 -07001157 private void handleVmOrFwdSetError(int msgId) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001158 if (mChangingVMorFwdDueToProviderChange) {
1159 mVMOrFwdSetError = msgId;
1160 mChangingVMorFwdDueToProviderChange = false;
1161 switchToPreviousVoicemailProvider();
1162 return;
1163 }
1164 mChangingVMorFwdDueToProviderChange = false;
1165 showVMDialog(msgId);
1166 updateVoiceNumberField();
1167 }
1168
1169 /**
1170 * Called when Voicemail Provider and its forwarding settings were successfully finished.
1171 * This updates a bunch of variables and show "success" dialog.
1172 */
Andrew Leee438b312014-10-29 16:59:15 -07001173 private void handleVmAndFwdSetSuccess(int msg) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001174 if (DBG) {
Andrew Leee438b312014-10-29 16:59:15 -07001175 log("handleVmAndFwdSetSuccess(). current voicemail provider key: "
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001176 + getCurrentVoicemailProviderKey());
1177 }
1178 mPreviousVMProviderKey = getCurrentVoicemailProviderKey();
1179 mChangingVMorFwdDueToProviderChange = false;
1180 showVMDialog(msg);
1181 updateVoiceNumberField();
1182 }
1183
1184 /**
1185 * Update the voicemail number from what we've recorded on the sim.
1186 */
1187 private void updateVoiceNumberField() {
1188 if (DBG) {
1189 log("updateVoiceNumberField(). mSubMenuVoicemailSettings=" + mSubMenuVoicemailSettings);
1190 }
1191 if (mSubMenuVoicemailSettings == null) {
1192 return;
1193 }
1194
1195 mOldVmNumber = mPhone.getVoiceMailNumber();
1196 if (mOldVmNumber == null) {
1197 mOldVmNumber = "";
1198 }
1199 mSubMenuVoicemailSettings.setPhoneNumber(mOldVmNumber);
1200 final String summary = (mOldVmNumber.length() > 0) ? mOldVmNumber :
1201 getString(R.string.voicemail_number_not_set);
1202 mSubMenuVoicemailSettings.setSummary(summary);
1203 }
1204
1205 /*
1206 * Helper Methods for Activity class.
1207 * The initial query commands are split into two pieces now
1208 * for individual expansion. This combined with the ability
1209 * to cancel queries allows for a much better user experience,
1210 * and also ensures that the user only waits to update the
1211 * data that is relevant.
1212 */
1213
1214 @Override
1215 protected void onPrepareDialog(int id, Dialog dialog) {
1216 super.onPrepareDialog(id, dialog);
1217 mCurrentDialogId = id;
1218 }
1219
1220 // dialog creation method, called by showDialog()
1221 @Override
1222 protected Dialog onCreateDialog(int id) {
1223 if ((id == VM_RESPONSE_ERROR) || (id == VM_NOCHANGE_ERROR) ||
1224 (id == FW_SET_RESPONSE_ERROR) || (id == FW_GET_RESPONSE_ERROR) ||
1225 (id == VOICEMAIL_DIALOG_CONFIRM)) {
1226
1227 AlertDialog.Builder b = new AlertDialog.Builder(this);
1228
1229 int msgId;
1230 int titleId = R.string.error_updating_title;
1231 switch (id) {
1232 case VOICEMAIL_DIALOG_CONFIRM:
1233 msgId = R.string.vm_changed;
1234 titleId = R.string.voicemail;
1235 // Set Button 2
1236 b.setNegativeButton(R.string.close_dialog, this);
1237 break;
1238 case VM_NOCHANGE_ERROR:
1239 // even though this is technically an error,
1240 // keep the title friendly.
1241 msgId = R.string.no_change;
1242 titleId = R.string.voicemail;
1243 // Set Button 2
1244 b.setNegativeButton(R.string.close_dialog, this);
1245 break;
1246 case VM_RESPONSE_ERROR:
1247 msgId = R.string.vm_change_failed;
1248 // Set Button 1
1249 b.setPositiveButton(R.string.close_dialog, this);
1250 break;
1251 case FW_SET_RESPONSE_ERROR:
1252 msgId = R.string.fw_change_failed;
1253 // Set Button 1
1254 b.setPositiveButton(R.string.close_dialog, this);
1255 break;
1256 case FW_GET_RESPONSE_ERROR:
1257 msgId = R.string.fw_get_in_vm_failed;
1258 b.setPositiveButton(R.string.alert_dialog_yes, this);
1259 b.setNegativeButton(R.string.alert_dialog_no, this);
1260 break;
1261 default:
1262 msgId = R.string.exception_error;
1263 // Set Button 3, tells the activity that the error is
1264 // not recoverable on dialog exit.
1265 b.setNeutralButton(R.string.close_dialog, this);
1266 break;
1267 }
1268
1269 b.setTitle(getText(titleId));
1270 String message = getText(msgId).toString();
1271 b.setMessage(message);
1272 b.setCancelable(false);
1273 AlertDialog dialog = b.create();
1274
1275 // make the dialog more obvious by bluring the background.
1276 dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
1277
1278 return dialog;
1279 } else if (id == VOICEMAIL_FWD_SAVING_DIALOG || id == VOICEMAIL_FWD_READING_DIALOG ||
1280 id == VOICEMAIL_REVERTING_DIALOG) {
1281 ProgressDialog dialog = new ProgressDialog(this);
1282 dialog.setTitle(getText(R.string.updating_title));
1283 dialog.setIndeterminate(true);
1284 dialog.setCancelable(false);
1285 dialog.setMessage(getText(
1286 id == VOICEMAIL_FWD_SAVING_DIALOG ? R.string.updating_settings :
1287 (id == VOICEMAIL_REVERTING_DIALOG ? R.string.reverting_settings :
1288 R.string.reading_settings)));
1289 return dialog;
1290 }
1291
1292
1293 return null;
1294 }
1295
1296 // This is a method implemented for DialogInterface.OnClickListener.
1297 // Used with the error dialog to close the app, voicemail dialog to just dismiss.
1298 // Close button is mapped to BUTTON_POSITIVE for the errors that close the activity,
1299 // while those that are mapped to BUTTON_NEUTRAL only move the preference focus.
1300 public void onClick(DialogInterface dialog, int which) {
1301 dialog.dismiss();
1302 switch (which){
1303 case DialogInterface.BUTTON_NEUTRAL:
1304 if (DBG) log("Neutral button");
1305 break;
1306 case DialogInterface.BUTTON_NEGATIVE:
1307 if (DBG) log("Negative button");
1308 if (mCurrentDialogId == FW_GET_RESPONSE_ERROR) {
1309 // We failed to get current forwarding settings and the user
1310 // does not wish to continue.
1311 switchToPreviousVoicemailProvider();
1312 }
1313 break;
1314 case DialogInterface.BUTTON_POSITIVE:
1315 if (DBG) log("Positive button");
1316 if (mCurrentDialogId == FW_GET_RESPONSE_ERROR) {
1317 // We failed to get current forwarding settings but the user
1318 // wishes to continue changing settings to the new vm provider
1319 saveVoiceMailAndForwardingNumberStage2();
1320 } else {
1321 finish();
1322 }
1323 return;
1324 default:
1325 // just let the dialog close and go back to the input
1326 }
1327 // In all dialogs, all buttons except BUTTON_POSITIVE lead to the end of user interaction
1328 // with settings UI. If we were called to explicitly configure voice mail then
1329 // we finish the settings activity here to come back to whatever the user was doing.
1330 if (getIntent().getAction().equals(ACTION_ADD_VOICEMAIL)) {
1331 finish();
1332 }
1333 }
1334
1335 // set the app state with optional status.
1336 private void showVMDialog(int msgStatus) {
1337 switch (msgStatus) {
1338 // It's a bit worrisome to punt in the error cases here when we're
1339 // not in the foreground; maybe toast instead?
1340 case MSG_VM_EXCEPTION:
1341 showDialogIfForeground(VM_RESPONSE_ERROR);
1342 break;
1343 case MSG_FW_SET_EXCEPTION:
1344 showDialogIfForeground(FW_SET_RESPONSE_ERROR);
1345 break;
1346 case MSG_FW_GET_EXCEPTION:
1347 showDialogIfForeground(FW_GET_RESPONSE_ERROR);
1348 break;
1349 case MSG_VM_NOCHANGE:
1350 showDialogIfForeground(VM_NOCHANGE_ERROR);
1351 break;
1352 case MSG_VM_OK:
1353 showDialogIfForeground(VOICEMAIL_DIALOG_CONFIRM);
1354 break;
1355 case MSG_OK:
1356 default:
1357 // This should never happen.
1358 }
1359 }
1360
1361 /*
1362 * Activity class methods
1363 */
1364
1365 @Override
1366 protected void onCreate(Bundle icicle) {
1367 super.onCreate(icicle);
1368 if (DBG) log("onCreate(). Intent: " + getIntent());
1369 mPhone = PhoneGlobals.getPhone();
Tyler Gunnbaee2952014-09-10 16:01:02 -07001370 mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
1371
Tyler Gunnbaee2952014-09-10 16:01:02 -07001372 // Show the voicemail preference in onResume if the calling intent specifies the
1373 // ACTION_ADD_VOICEMAIL action.
1374 mShowVoicemailPreference = (icicle == null) &&
1375 getIntent().getAction().equals(ACTION_ADD_VOICEMAIL);
1376 }
1377
1378 private void initPhoneAccountPreferences() {
Andrew Leece8ae2a2014-09-10 10:41:48 -07001379 mPhoneAccountSettingsPreference = findPreference(PHONE_ACCOUNT_SETTINGS_KEY);
Tyler Gunnbaee2952014-09-10 16:01:02 -07001380
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001381 TelecomManager telecomManager = TelecomManager.from(this);
Andrew Lee93c345f2014-10-27 15:25:07 -07001382 TelephonyManager telephonyManager =
1383 (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
Tyler Gunnbaee2952014-09-10 16:01:02 -07001384
Andrew Lee93c345f2014-10-27 15:25:07 -07001385 if ((telecomManager.getSimCallManagers().isEmpty() && !SipUtil.isVoipSupported(this))
1386 || telephonyManager.getPhoneCount() > 1) {
Andrew Leece8ae2a2014-09-10 10:41:48 -07001387 getPreferenceScreen().removePreference(mPhoneAccountSettingsPreference);
Tyler Gunnbaee2952014-09-10 16:01:02 -07001388 }
1389 }
1390
1391 private boolean canLaunchIntent(Intent intent) {
1392 PackageManager pm = getPackageManager();
1393 return pm.resolveActivity(intent, PackageManager.GET_ACTIVITIES) != null;
1394 }
1395
Tyler Gunnbaee2952014-09-10 16:01:02 -07001396 @Override
1397 protected void onResume() {
1398 super.onResume();
1399 mForeground = true;
1400
1401 PreferenceScreen preferenceScreen = getPreferenceScreen();
1402 if (preferenceScreen != null) {
1403 preferenceScreen.removeAll();
1404 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001405
1406 addPreferencesFromResource(R.xml.call_feature_setting);
Andrew Leedb2fe562014-09-03 15:40:43 -07001407 initPhoneAccountPreferences();
1408
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001409 PreferenceScreen prefSet = getPreferenceScreen();
Andrew Lee64a7d792014-10-15 17:38:38 -07001410 mSubMenuVoicemailSettings = (EditPhoneNumberPreference) findPreference(BUTTON_VOICEMAIL_KEY);
1411 mSubMenuVoicemailSettings.setParentActivity(this, VOICEMAIL_PREF_ID, this);
1412 mSubMenuVoicemailSettings.setDialogOnClosedListener(this);
1413 mSubMenuVoicemailSettings.setDialogTitle(R.string.voicemail_settings_number_label);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001414
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001415 mButtonDTMF = (ListPreference) findPreference(BUTTON_DTMF_KEY);
1416 mButtonAutoRetry = (CheckBoxPreference) findPreference(BUTTON_RETRY_KEY);
1417 mButtonHAC = (CheckBoxPreference) findPreference(BUTTON_HAC_KEY);
1418 mButtonTTY = (ListPreference) findPreference(BUTTON_TTY_KEY);
1419 mVoicemailProviders = (ListPreference) findPreference(BUTTON_VOICEMAIL_PROVIDER_KEY);
Andrew Lee312e8172014-10-23 17:01:36 -07001420 mEnableVideoCalling = (CheckBoxPreference) findPreference(ENABLE_VIDEO_CALLING_KEY);
Andrew Lee2170a972014-08-13 18:13:01 -07001421
Andrew Lee2c027892014-10-29 11:29:54 -07001422 mVoicemailProviders.setOnPreferenceChangeListener(this);
1423 mVoicemailSettingsScreen =
1424 (PreferenceScreen) findPreference(VOICEMAIL_SETTING_SCREEN_PREF_KEY);
1425 mVoicemailSettings = (PreferenceScreen)findPreference(BUTTON_VOICEMAIL_SETTING_KEY);
1426 mVoicemailNotificationVibrate =
1427 (CheckBoxPreference) findPreference(BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY);
1428 initVoiceMailProviders();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001429
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001430
Andrew Lee64a7d792014-10-15 17:38:38 -07001431 if (getResources().getBoolean(R.bool.dtmf_type_enabled)) {
1432 mButtonDTMF.setOnPreferenceChangeListener(this);
1433 int dtmf = Settings.System.getInt(getContentResolver(),
1434 Settings.System.DTMF_TONE_TYPE_WHEN_DIALING, Constants.DTMF_TONE_TYPE_NORMAL);
1435 mButtonDTMF.setValueIndex(dtmf);
1436 } else {
1437 prefSet.removePreference(mButtonDTMF);
1438 mButtonDTMF = null;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001439 }
1440
Andrew Lee64a7d792014-10-15 17:38:38 -07001441 if (getResources().getBoolean(R.bool.auto_retry_enabled)) {
1442 mButtonAutoRetry.setOnPreferenceChangeListener(this);
1443 int autoretry = Settings.Global.getInt(
1444 getContentResolver(), Settings.Global.CALL_AUTO_RETRY, 0);
1445 mButtonAutoRetry.setChecked(autoretry != 0);
1446 } else {
1447 prefSet.removePreference(mButtonAutoRetry);
1448 mButtonAutoRetry = null;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001449 }
1450
Andrew Lee64a7d792014-10-15 17:38:38 -07001451 if (getResources().getBoolean(R.bool.hac_enabled)) {
1452 mButtonHAC.setOnPreferenceChangeListener(this);
1453 int hac = Settings.System.getInt(getContentResolver(), Settings.System.HEARING_AID, 0);
1454 mButtonHAC.setChecked(hac != 0);
1455 } else {
1456 prefSet.removePreference(mButtonHAC);
1457 mButtonHAC = null;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001458 }
1459
Andrew Lee64a7d792014-10-15 17:38:38 -07001460 TelecomManager telecomManager = TelecomManager.from(this);
1461 if (telecomManager != null && telecomManager.isTtySupported()) {
1462 mButtonTTY.setOnPreferenceChangeListener(this);
1463 int settingsTtyMode = Settings.Secure.getInt(getContentResolver(),
1464 Settings.Secure.PREFERRED_TTY_MODE,
1465 TelecomManager.TTY_MODE_OFF);
1466 mButtonTTY.setValue(Integer.toString(settingsTtyMode));
1467 updatePreferredTtyModeSummary(settingsTtyMode);
1468 } else {
1469 prefSet.removePreference(mButtonTTY);
1470 mButtonTTY = null;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001471 }
1472
1473 if (!getResources().getBoolean(R.bool.world_phone)) {
1474 Preference options = prefSet.findPreference(BUTTON_CDMA_OPTIONS);
Andrew Lee2170a972014-08-13 18:13:01 -07001475 if (options != null) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001476 prefSet.removePreference(options);
Andrew Lee2170a972014-08-13 18:13:01 -07001477 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001478 options = prefSet.findPreference(BUTTON_GSM_UMTS_OPTIONS);
Andrew Lee2170a972014-08-13 18:13:01 -07001479 if (options != null) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001480 prefSet.removePreference(options);
Andrew Lee2170a972014-08-13 18:13:01 -07001481 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001482
1483 int phoneType = mPhone.getPhoneType();
1484 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1485 Preference fdnButton = prefSet.findPreference(BUTTON_FDN_KEY);
Andrew Lee2170a972014-08-13 18:13:01 -07001486 if (fdnButton != null) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001487 prefSet.removePreference(fdnButton);
Andrew Lee2170a972014-08-13 18:13:01 -07001488 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001489 if (!getResources().getBoolean(R.bool.config_voice_privacy_disable)) {
1490 addPreferencesFromResource(R.xml.cdma_call_privacy);
1491 }
1492 } else if (phoneType == PhoneConstants.PHONE_TYPE_GSM) {
Andrew Lee2170a972014-08-13 18:13:01 -07001493 if (getResources().getBoolean(R.bool.config_additional_call_setting)) {
Etan Cohen0ca1c802014-07-07 15:35:48 -07001494 addPreferencesFromResource(R.xml.gsm_umts_call_options);
1495 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001496 } else {
1497 throw new IllegalStateException("Unexpected phone type: " + phoneType);
1498 }
1499 }
1500
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001501 // check the intent that started this activity and pop up the voicemail
1502 // dialog if we've been asked to.
1503 // If we have at least one non default VM provider registered then bring up
1504 // the selection for the VM provider, otherwise bring up a VM number dialog.
1505 // We only bring up the dialog the first time we are called (not after orientation change)
Andrew Lee2c027892014-10-29 11:29:54 -07001506 if (mShowVoicemailPreference) {
Tyler Gunnbaee2952014-09-10 16:01:02 -07001507 if (DBG) {
1508 log("ACTION_ADD_VOICEMAIL Intent is thrown. current VM data size: "
1509 + mVMProvidersData.size());
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001510 }
Tyler Gunnbaee2952014-09-10 16:01:02 -07001511 if (mVMProvidersData.size() > 1) {
1512 simulatePreferenceClick(mVoicemailProviders);
1513 } else {
1514 onPreferenceChange(mVoicemailProviders, DEFAULT_VM_PROVIDER_KEY);
1515 mVoicemailProviders.setValue(DEFAULT_VM_PROVIDER_KEY);
1516 }
1517 mShowVoicemailPreference = false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001518 }
Tyler Gunnbaee2952014-09-10 16:01:02 -07001519
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001520 updateVoiceNumberField();
1521 mVMProviderSettingsForced = false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001522
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001523 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(
1524 mPhone.getContext());
1525 if (migrateVoicemailVibrationSettingsIfNeeded(prefs)) {
1526 mVoicemailNotificationVibrate.setChecked(prefs.getBoolean(
1527 BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY, false));
1528 }
1529
Andrew Lee312e8172014-10-23 17:01:36 -07001530 if (ImsManager.isVtEnabledByPlatform(mPhone.getContext()) && ENABLE_VT_FLAG) {
1531 boolean currentValue =
1532 ImsManager.isEnhanced4gLteModeSettingEnabledByUser(mPhone.getContext())
1533 ? PhoneGlobals.getInstance().phoneMgr.isVideoCallingEnabled() : false;
1534 mEnableVideoCalling.setChecked(currentValue);
Andrew Lee77527ac2014-10-21 16:57:39 -07001535 mEnableVideoCalling.setOnPreferenceChangeListener(this);
1536 } else {
1537 prefSet.removePreference(mEnableVideoCalling);
1538 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001539 }
1540
1541 // Migrate settings from BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_WHEN_KEY to
1542 // BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY, if the latter does not exist.
1543 // Returns true if migration was performed.
1544 public static boolean migrateVoicemailVibrationSettingsIfNeeded(SharedPreferences prefs) {
1545 if (!prefs.contains(BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY)) {
1546 String vibrateWhen = prefs.getString(
1547 BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_WHEN_KEY, VOICEMAIL_VIBRATION_NEVER);
1548 // If vibrateWhen is always, then voicemailVibrate should be True.
1549 // otherwise if vibrateWhen is "only in silent mode", or "never", then
1550 // voicemailVibrate = False.
1551 boolean voicemailVibrate = vibrateWhen.equals(VOICEMAIL_VIBRATION_ALWAYS);
1552 final SharedPreferences.Editor editor = prefs.edit();
1553 editor.putBoolean(BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY, voicemailVibrate);
1554 editor.commit();
1555 return true;
1556 }
1557 return false;
1558 }
1559
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001560 private void handleTTYChange(Preference preference, Object objValue) {
1561 int buttonTtyMode;
1562 buttonTtyMode = Integer.valueOf((String) objValue).intValue();
1563 int settingsTtyMode = android.provider.Settings.Secure.getInt(
1564 getContentResolver(),
Sailesh Nepalbf900542014-07-15 16:18:32 -07001565 android.provider.Settings.Secure.PREFERRED_TTY_MODE,
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001566 TelecomManager.TTY_MODE_OFF);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001567 if (DBG) log("handleTTYChange: requesting set TTY mode enable (TTY) to" +
1568 Integer.toString(buttonTtyMode));
1569
1570 if (buttonTtyMode != settingsTtyMode) {
1571 switch(buttonTtyMode) {
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001572 case TelecomManager.TTY_MODE_OFF:
1573 case TelecomManager.TTY_MODE_FULL:
1574 case TelecomManager.TTY_MODE_HCO:
1575 case TelecomManager.TTY_MODE_VCO:
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001576 android.provider.Settings.Secure.putInt(getContentResolver(),
1577 android.provider.Settings.Secure.PREFERRED_TTY_MODE, buttonTtyMode);
1578 break;
1579 default:
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001580 buttonTtyMode = TelecomManager.TTY_MODE_OFF;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001581 }
1582
1583 mButtonTTY.setValue(Integer.toString(buttonTtyMode));
1584 updatePreferredTtyModeSummary(buttonTtyMode);
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001585 Intent ttyModeChanged = new Intent(TelecomManager.ACTION_TTY_PREFERRED_MODE_CHANGED);
1586 ttyModeChanged.putExtra(TelecomManager.EXTRA_TTY_PREFERRED_MODE, buttonTtyMode);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001587 sendBroadcastAsUser(ttyModeChanged, UserHandle.ALL);
1588 }
1589 }
1590
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001591 private void updatePreferredTtyModeSummary(int TtyMode) {
1592 String [] txts = getResources().getStringArray(R.array.tty_mode_entries);
1593 switch(TtyMode) {
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001594 case TelecomManager.TTY_MODE_OFF:
1595 case TelecomManager.TTY_MODE_HCO:
1596 case TelecomManager.TTY_MODE_VCO:
1597 case TelecomManager.TTY_MODE_FULL:
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001598 mButtonTTY.setSummary(txts[TtyMode]);
1599 break;
1600 default:
1601 mButtonTTY.setEnabled(false);
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001602 mButtonTTY.setSummary(txts[TelecomManager.TTY_MODE_OFF]);
Sailesh Nepalbf900542014-07-15 16:18:32 -07001603 break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001604 }
1605 }
1606
1607 private static void log(String msg) {
1608 Log.d(LOG_TAG, msg);
1609 }
1610
1611 /**
1612 * Updates the look of the VM preference widgets based on current VM provider settings.
1613 * Note that the provider name is loaded form the found activity via loadLabel in
1614 * {@link #initVoiceMailProviders()} in order for it to be localizable.
1615 */
1616 private void updateVMPreferenceWidgets(String currentProviderSetting) {
1617 final String key = currentProviderSetting;
1618 final VoiceMailProvider provider = mVMProvidersData.get(key);
1619
1620 /* This is the case when we are coming up on a freshly wiped phone and there is no
1621 persisted value for the list preference mVoicemailProviders.
1622 In this case we want to show the UI asking the user to select a voicemail provider as
1623 opposed to silently falling back to default one. */
1624 if (provider == null) {
1625 if (DBG) {
1626 log("updateVMPreferenceWidget: provider for the key \"" + key + "\" is null.");
1627 }
1628 mVoicemailProviders.setSummary(getString(R.string.sum_voicemail_choose_provider));
1629 mVoicemailSettings.setEnabled(false);
1630 mVoicemailSettings.setIntent(null);
1631
1632 mVoicemailNotificationVibrate.setEnabled(false);
1633 } else {
1634 if (DBG) {
1635 log("updateVMPreferenceWidget: provider for the key \"" + key + "\".."
1636 + "name: " + provider.name
1637 + ", intent: " + provider.intent);
1638 }
1639 final String providerName = provider.name;
1640 mVoicemailProviders.setSummary(providerName);
1641 mVoicemailSettings.setEnabled(true);
1642 mVoicemailSettings.setIntent(provider.intent);
1643
1644 mVoicemailNotificationVibrate.setEnabled(true);
1645 }
1646 }
1647
1648 /**
1649 * Enumerates existing VM providers and puts their data into the list and populates
1650 * the preference list objects with their names.
1651 * In case we are called with ACTION_ADD_VOICEMAIL intent the intent may have
1652 * an extra string called IGNORE_PROVIDER_EXTRA with "package.activityName" of the provider
1653 * which should be hidden when we bring up the list of possible VM providers to choose.
1654 */
1655 private void initVoiceMailProviders() {
1656 if (DBG) log("initVoiceMailProviders()");
1657 mPerProviderSavedVMNumbers =
1658 this.getApplicationContext().getSharedPreferences(
1659 VM_NUMBERS_SHARED_PREFERENCES_NAME, MODE_PRIVATE);
1660
1661 String providerToIgnore = null;
1662 if (getIntent().getAction().equals(ACTION_ADD_VOICEMAIL)) {
1663 if (getIntent().hasExtra(IGNORE_PROVIDER_EXTRA)) {
1664 providerToIgnore = getIntent().getStringExtra(IGNORE_PROVIDER_EXTRA);
1665 }
1666 if (DBG) log("Found ACTION_ADD_VOICEMAIL. providerToIgnore=" + providerToIgnore);
1667 if (providerToIgnore != null) {
1668 // IGNORE_PROVIDER_EXTRA implies we want to remove the choice from the list.
1669 deleteSettingsForVoicemailProvider(providerToIgnore);
1670 }
1671 }
1672
1673 mVMProvidersData.clear();
1674
1675 // Stick the default element which is always there
1676 final String myCarrier = getString(R.string.voicemail_default);
1677 mVMProvidersData.put(DEFAULT_VM_PROVIDER_KEY, new VoiceMailProvider(myCarrier, null));
1678
1679 // Enumerate providers
1680 PackageManager pm = getPackageManager();
1681 Intent intent = new Intent();
1682 intent.setAction(ACTION_CONFIGURE_VOICEMAIL);
1683 List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
1684 int len = resolveInfos.size() + 1; // +1 for the default choice we will insert.
1685
1686 // Go through the list of discovered providers populating the data map
1687 // skip the provider we were instructed to ignore if there was one
1688 for (int i = 0; i < resolveInfos.size(); i++) {
1689 final ResolveInfo ri= resolveInfos.get(i);
1690 final ActivityInfo currentActivityInfo = ri.activityInfo;
1691 final String key = makeKeyForActivity(currentActivityInfo);
1692 if (key.equals(providerToIgnore)) {
1693 if (DBG) log("Ignoring key: " + key);
1694 len--;
1695 continue;
1696 }
1697 if (DBG) log("Loading key: " + key);
1698 final String nameForDisplay = ri.loadLabel(pm).toString();
1699 Intent providerIntent = new Intent();
1700 providerIntent.setAction(ACTION_CONFIGURE_VOICEMAIL);
1701 providerIntent.setClassName(currentActivityInfo.packageName,
1702 currentActivityInfo.name);
1703 if (DBG) {
1704 log("Store loaded VoiceMailProvider. key: " + key
1705 + " -> name: " + nameForDisplay + ", intent: " + providerIntent);
1706 }
1707 mVMProvidersData.put(
1708 key,
1709 new VoiceMailProvider(nameForDisplay, providerIntent));
1710
1711 }
1712
1713 // Now we know which providers to display - create entries and values array for
1714 // the list preference
1715 String [] entries = new String [len];
1716 String [] values = new String [len];
1717 entries[0] = myCarrier;
1718 values[0] = DEFAULT_VM_PROVIDER_KEY;
1719 int entryIdx = 1;
1720 for (int i = 0; i < resolveInfos.size(); i++) {
1721 final String key = makeKeyForActivity(resolveInfos.get(i).activityInfo);
1722 if (!mVMProvidersData.containsKey(key)) {
1723 continue;
1724 }
1725 entries[entryIdx] = mVMProvidersData.get(key).name;
1726 values[entryIdx] = key;
1727 entryIdx++;
1728 }
1729
1730 // ListPreference is now updated.
1731 mVoicemailProviders.setEntries(entries);
1732 mVoicemailProviders.setEntryValues(values);
1733
1734 // Remember the current Voicemail Provider key as a "previous" key. This will be used
1735 // when we fail to update Voicemail Provider, which requires rollback.
1736 // We will update this when the VM Provider setting is successfully updated.
1737 mPreviousVMProviderKey = getCurrentVoicemailProviderKey();
1738 if (DBG) log("Set up the first mPreviousVMProviderKey: " + mPreviousVMProviderKey);
1739
1740 // Finally update the preference texts.
1741 updateVMPreferenceWidgets(mPreviousVMProviderKey);
1742 }
1743
1744 private String makeKeyForActivity(ActivityInfo ai) {
1745 return ai.name;
1746 }
1747
1748 /**
1749 * Simulates user clicking on a passed preference.
1750 * Usually needed when the preference is a dialog preference and we want to invoke
1751 * a dialog for this preference programmatically.
Santos Cordonda120f42014-08-06 04:44:34 -07001752 * TODO: figure out if there is a cleaner way to cause preference dlg to come up
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001753 */
1754 private void simulatePreferenceClick(Preference preference) {
1755 // Go through settings until we find our setting
1756 // and then simulate a click on it to bring up the dialog
1757 final ListAdapter adapter = getPreferenceScreen().getRootAdapter();
1758 for (int idx = 0; idx < adapter.getCount(); idx++) {
1759 if (adapter.getItem(idx) == preference) {
1760 getPreferenceScreen().onItemClick(this.getListView(),
1761 null, idx, adapter.getItemId(idx));
1762 break;
1763 }
1764 }
1765 }
1766
1767 /**
1768 * Saves new VM provider settings associating them with the currently selected
1769 * provider if settings are different than the ones already stored for this
1770 * provider.
1771 * Later on these will be used when the user switches a provider.
1772 */
1773 private void maybeSaveSettingsForVoicemailProvider(String key,
Andrew Leeb490d732014-10-27 15:00:41 -07001774 VoicemailProviderSettings newSettings) {
Andrew Leeb490d732014-10-27 15:00:41 -07001775 final VoicemailProviderSettings curSettings = loadSettingsForVoiceMailProvider(key);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001776 if (newSettings.equals(curSettings)) {
1777 if (DBG) {
1778 log("maybeSaveSettingsForVoicemailProvider:"
1779 + " Not saving setting for " + key + " since they have not changed");
1780 }
1781 return;
1782 }
1783 if (DBG) log("Saving settings for " + key + ": " + newSettings.toString());
1784 Editor editor = mPerProviderSavedVMNumbers.edit();
Andrew Leeb490d732014-10-27 15:00:41 -07001785 editor.putString(key + VM_NUMBER_TAG, newSettings.getVoicemailNumber());
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001786 String fwdKey = key + FWD_SETTINGS_TAG;
Andrew Leeb490d732014-10-27 15:00:41 -07001787 CallForwardInfo[] s = newSettings.getForwardingSettings();
1788 if (s != VoicemailProviderSettings.NO_FORWARDING) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001789 editor.putInt(fwdKey + FWD_SETTINGS_LENGTH_TAG, s.length);
1790 for (int i = 0; i < s.length; i++) {
1791 final String settingKey = fwdKey + FWD_SETTING_TAG + String.valueOf(i);
1792 final CallForwardInfo fi = s[i];
1793 editor.putInt(settingKey + FWD_SETTING_STATUS, fi.status);
1794 editor.putInt(settingKey + FWD_SETTING_REASON, fi.reason);
1795 editor.putString(settingKey + FWD_SETTING_NUMBER, fi.number);
1796 editor.putInt(settingKey + FWD_SETTING_TIME, fi.timeSeconds);
1797 }
1798 } else {
1799 editor.putInt(fwdKey + FWD_SETTINGS_LENGTH_TAG, 0);
1800 }
1801 editor.apply();
1802 }
1803
1804 /**
1805 * Returns settings previously stored for the currently selected
1806 * voice mail provider. If none is stored returns null.
1807 * If the user switches to a voice mail provider and we have settings
1808 * stored for it we will automatically change the phone's voice mail number
1809 * and forwarding number to the stored one. Otherwise we will bring up provider's configuration
1810 * UI.
1811 */
Andrew Leeb490d732014-10-27 15:00:41 -07001812 private VoicemailProviderSettings loadSettingsForVoiceMailProvider(String key) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001813 final String vmNumberSetting = mPerProviderSavedVMNumbers.getString(key + VM_NUMBER_TAG,
1814 null);
1815 if (vmNumberSetting == null) {
1816 Log.w(LOG_TAG, "VoiceMailProvider settings for the key \"" + key + "\""
1817 + " was not found. Returning null.");
1818 return null;
1819 }
1820
Andrew Leeb490d732014-10-27 15:00:41 -07001821 CallForwardInfo[] cfi = VoicemailProviderSettings.NO_FORWARDING;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001822 String fwdKey = key + FWD_SETTINGS_TAG;
1823 final int fwdLen = mPerProviderSavedVMNumbers.getInt(fwdKey + FWD_SETTINGS_LENGTH_TAG, 0);
1824 if (fwdLen > 0) {
1825 cfi = new CallForwardInfo[fwdLen];
1826 for (int i = 0; i < cfi.length; i++) {
1827 final String settingKey = fwdKey + FWD_SETTING_TAG + String.valueOf(i);
1828 cfi[i] = new CallForwardInfo();
1829 cfi[i].status = mPerProviderSavedVMNumbers.getInt(
1830 settingKey + FWD_SETTING_STATUS, 0);
1831 cfi[i].reason = mPerProviderSavedVMNumbers.getInt(
1832 settingKey + FWD_SETTING_REASON,
1833 CommandsInterface.CF_REASON_ALL_CONDITIONAL);
1834 cfi[i].serviceClass = CommandsInterface.SERVICE_CLASS_VOICE;
1835 cfi[i].toa = PhoneNumberUtils.TOA_International;
1836 cfi[i].number = mPerProviderSavedVMNumbers.getString(
1837 settingKey + FWD_SETTING_NUMBER, "");
1838 cfi[i].timeSeconds = mPerProviderSavedVMNumbers.getInt(
1839 settingKey + FWD_SETTING_TIME, 20);
1840 }
1841 }
1842
Andrew Leeb490d732014-10-27 15:00:41 -07001843 VoicemailProviderSettings settings = new VoicemailProviderSettings(vmNumberSetting, cfi);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001844 if (DBG) log("Loaded settings for " + key + ": " + settings.toString());
1845 return settings;
1846 }
1847
1848 /**
1849 * Deletes settings for the specified provider.
1850 */
1851 private void deleteSettingsForVoicemailProvider(String key) {
1852 if (DBG) log("Deleting settings for" + key);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001853 mPerProviderSavedVMNumbers.edit()
1854 .putString(key + VM_NUMBER_TAG, null)
1855 .putInt(key + FWD_SETTINGS_TAG + FWD_SETTINGS_LENGTH_TAG, 0)
1856 .commit();
1857 }
1858
1859 private String getCurrentVoicemailProviderKey() {
1860 final String key = mVoicemailProviders.getValue();
1861 return (key != null) ? key : DEFAULT_VM_PROVIDER_KEY;
1862 }
1863
1864 @Override
1865 public boolean onOptionsItemSelected(MenuItem item) {
1866 final int itemId = item.getItemId();
1867 if (itemId == android.R.id.home) { // See ActionBar#setDisplayHomeAsUpEnabled()
Yorke Leef2d0cac2013-09-09 19:42:56 -07001868 onBackPressed();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001869 return true;
1870 }
1871 return super.onOptionsItemSelected(item);
1872 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001873 /**
1874 * Finish current Activity and go up to the top level Settings ({@link CallFeaturesSetting}).
1875 * This is useful for implementing "HomeAsUp" capability for second-level Settings.
1876 */
1877 public static void goUpToTopLevelSetting(Activity activity) {
1878 Intent intent = new Intent(activity, CallFeaturesSetting.class);
1879 intent.setAction(Intent.ACTION_MAIN);
1880 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
1881 activity.startActivity(intent);
1882 activity.finish();
1883 }
1884}