blob: b7f2d55bc6864286e63a5dfb50afdeb8fbb3d111 [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";
117 // Extra put in the return from VM provider config containing voicemail number to set
118 public static final String VM_NUMBER_EXTRA = "com.android.phone.VoicemailNumber";
119 // Extra put in the return from VM provider config containing call forwarding number to set
120 public static final String FWD_NUMBER_EXTRA = "com.android.phone.ForwardingNumber";
121 // Extra put in the return from VM provider config containing call forwarding number to set
122 public static final String FWD_NUMBER_TIME_EXTRA = "com.android.phone.ForwardingNumberTime";
123 // If the VM provider returns non null value in this extra we will force the user to
124 // choose another VM provider
125 public static final String SIGNOUT_EXTRA = "com.android.phone.Signout";
126 //Information about logical "up" Activity
127 private static final String UP_ACTIVITY_PACKAGE = "com.android.dialer";
128 private static final String UP_ACTIVITY_CLASS =
129 "com.android.dialer.DialtactsActivity";
130
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700131 // Suffix appended to provider key for storing vm number
132 public static final String VM_NUMBER_TAG = "#VMNumber";
133 // Suffix appended to provider key for storing forwarding settings
134 public static final String FWD_SETTINGS_TAG = "#FWDSettings";
135 // Suffix appended to forward settings key for storing length of settings array
136 public static final String FWD_SETTINGS_LENGTH_TAG = "#Length";
137 // Suffix appended to forward settings key for storing an individual setting
138 public static final String FWD_SETTING_TAG = "#Setting";
139 // Suffixes appended to forward setting key for storing an individual setting properties
140 public static final String FWD_SETTING_STATUS = "#Status";
141 public static final String FWD_SETTING_REASON = "#Reason";
142 public static final String FWD_SETTING_NUMBER = "#Number";
143 public static final String FWD_SETTING_TIME = "#Time";
144
145 // Key identifying the default vocie mail provider
146 public static final String DEFAULT_VM_PROVIDER_KEY = "";
147
148 /**
149 * String Extra put into ACTION_ADD_VOICEMAIL call to indicate which provider should be hidden
150 * in the list of providers presented to the user. This allows a provider which is being
151 * disabled (e.g. GV user logging out) to force the user to pick some other provider.
152 */
153 public static final String IGNORE_PROVIDER_EXTRA = "com.android.phone.ProviderToIgnore";
154
155 // string constants
156 private static final String NUM_PROJECTION[] = {CommonDataKinds.Phone.NUMBER};
157
158 // String keys for preference lookup
159 // TODO: Naming these "BUTTON_*" is confusing since they're not actually buttons(!)
Andrew Lee97708a42014-09-25 12:39:07 -0700160 private static final String VOICEMAIL_SETTING_SCREEN_PREF_KEY = "button_voicemail_category_key";
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700161 private static final String BUTTON_VOICEMAIL_KEY = "button_voicemail_key";
162 private static final String BUTTON_VOICEMAIL_PROVIDER_KEY = "button_voicemail_provider_key";
163 private static final String BUTTON_VOICEMAIL_SETTING_KEY = "button_voicemail_setting_key";
164 // New preference key for voicemail notification vibration
165 /* package */ static final String BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY =
166 "button_voicemail_notification_vibrate_key";
167 // Old preference key for voicemail notification vibration. Used for migration to the new
168 // preference key only.
169 /* package */ static final String BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_WHEN_KEY =
170 "button_voicemail_notification_vibrate_when_key";
171 /* package */ static final String BUTTON_VOICEMAIL_NOTIFICATION_RINGTONE_KEY =
172 "button_voicemail_notification_ringtone_key";
173 private static final String BUTTON_FDN_KEY = "button_fdn_key";
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700174
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700175 private static final String BUTTON_DTMF_KEY = "button_dtmf_settings";
176 private static final String BUTTON_RETRY_KEY = "button_auto_retry_key";
177 private static final String BUTTON_TTY_KEY = "button_tty_mode_key";
178 private static final String BUTTON_HAC_KEY = "button_hac_key";
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700179
180 private static final String BUTTON_GSM_UMTS_OPTIONS = "button_gsm_more_expand_key";
181 private static final String BUTTON_CDMA_OPTIONS = "button_cdma_more_expand_key";
182
183 private static final String VM_NUMBERS_SHARED_PREFERENCES_NAME = "vm_numbers";
184
Andrew Leedb2fe562014-09-03 15:40:43 -0700185 private static final String DEFAULT_OUTGOING_ACCOUNT_KEY = "default_outgoing_account";
Andrew Leece8ae2a2014-09-10 10:41:48 -0700186 private static final String PHONE_ACCOUNT_SETTINGS_KEY =
187 "phone_account_settings_preference_screen";
Andrew Leedb2fe562014-09-03 15:40:43 -0700188
Andrew Leedf14ead2014-10-17 14:22:52 -0700189 private static final String ENABLE_VIDEO_CALLING_KEY = "button_enable_video_calling";
190
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700191 private Intent mContactListIntent;
192
193 /** Event for Async voicemail change call */
194 private static final int EVENT_VOICEMAIL_CHANGED = 500;
195 private static final int EVENT_FORWARDING_CHANGED = 501;
196 private static final int EVENT_FORWARDING_GET_COMPLETED = 502;
197
Andrew Lee2170a972014-08-13 18:13:01 -0700198 private static final int MSG_UPDATE_VOICEMAIL_RINGTONE_SUMMARY = 1;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700199
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700200 public static final String HAC_KEY = "HACSetting";
201 public static final String HAC_VAL_ON = "ON";
202 public static final String HAC_VAL_OFF = "OFF";
203
204 /** Handle to voicemail pref */
205 private static final int VOICEMAIL_PREF_ID = 1;
206 private static final int VOICEMAIL_PROVIDER_CFG_ID = 2;
207
208 private Phone mPhone;
209
210 private AudioManager mAudioManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700211
212 private static final int VM_NOCHANGE_ERROR = 400;
213 private static final int VM_RESPONSE_ERROR = 500;
214 private static final int FW_SET_RESPONSE_ERROR = 501;
215 private static final int FW_GET_RESPONSE_ERROR = 502;
216
217
218 // dialog identifiers for voicemail
219 private static final int VOICEMAIL_DIALOG_CONFIRM = 600;
220 private static final int VOICEMAIL_FWD_SAVING_DIALOG = 601;
221 private static final int VOICEMAIL_FWD_READING_DIALOG = 602;
222 private static final int VOICEMAIL_REVERTING_DIALOG = 603;
223
224 // status message sent back from handlers
225 private static final int MSG_OK = 100;
226
227 // special statuses for voicemail controls.
228 private static final int MSG_VM_EXCEPTION = 400;
229 private static final int MSG_FW_SET_EXCEPTION = 401;
230 private static final int MSG_FW_GET_EXCEPTION = 402;
231 private static final int MSG_VM_OK = 600;
232 private static final int MSG_VM_NOCHANGE = 700;
233
234 // voicemail notification vibration string constants
235 private static final String VOICEMAIL_VIBRATION_ALWAYS = "always";
236 private static final String VOICEMAIL_VIBRATION_NEVER = "never";
237
238 private EditPhoneNumberPreference mSubMenuVoicemailSettings;
239
Andrew Lee2170a972014-08-13 18:13:01 -0700240 private Runnable mVoicemailRingtoneLookupRunnable;
241 private final Handler mVoicemailRingtoneLookupComplete = new Handler() {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700242 @Override
243 public void handleMessage(Message msg) {
244 switch (msg.what) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700245 case MSG_UPDATE_VOICEMAIL_RINGTONE_SUMMARY:
246 mVoicemailNotificationRingtone.setSummary((CharSequence) msg.obj);
247 break;
248 }
249 }
250 };
251
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700252 /** Whether dialpad plays DTMF tone or not. */
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700253 private CheckBoxPreference mButtonAutoRetry;
254 private CheckBoxPreference mButtonHAC;
255 private ListPreference mButtonDTMF;
256 private ListPreference mButtonTTY;
Andrew Leece8ae2a2014-09-10 10:41:48 -0700257 private Preference mPhoneAccountSettingsPreference;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700258 private ListPreference mVoicemailProviders;
Andrew Lee97708a42014-09-25 12:39:07 -0700259 private PreferenceScreen mVoicemailSettingsScreen;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700260 private PreferenceScreen mVoicemailSettings;
261 private Preference mVoicemailNotificationRingtone;
262 private CheckBoxPreference mVoicemailNotificationVibrate;
Andrew Leedb2fe562014-09-03 15:40:43 -0700263 private AccountSelectionPreference mDefaultOutgoingAccount;
Andrew Leedf14ead2014-10-17 14:22:52 -0700264 private CheckBoxPreference mEnableVideoCalling;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700265
266 private class VoiceMailProvider {
267 public VoiceMailProvider(String name, Intent intent) {
268 this.name = name;
269 this.intent = intent;
270 }
271 public String name;
272 public Intent intent;
273 }
274
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700275 private SharedPreferences mPerProviderSavedVMNumbers;
276
277 /**
278 * Results of reading forwarding settings
279 */
280 private CallForwardInfo[] mForwardingReadResults = null;
281
282 /**
283 * Result of forwarding number change.
284 * Keys are reasons (eg. unconditional forwarding).
285 */
286 private Map<Integer, AsyncResult> mForwardingChangeResults = null;
287
288 /**
289 * Expected CF read result types.
290 * This set keeps track of the CF types for which we've issued change
291 * commands so we can tell when we've received all of the responses.
292 */
293 private Collection<Integer> mExpectedChangeResultReasons = null;
294
295 /**
296 * Result of vm number change
297 */
298 private AsyncResult mVoicemailChangeResult = null;
299
300 /**
301 * Previous VM provider setting so we can return to it in case of failure.
302 */
303 private String mPreviousVMProviderKey = null;
304
305 /**
306 * Id of the dialog being currently shown.
307 */
308 private int mCurrentDialogId = 0;
309
310 /**
311 * Flag indicating that we are invoking settings for the voicemail provider programmatically
312 * due to vm provider change.
313 */
314 private boolean mVMProviderSettingsForced = false;
315
316 /**
317 * Flag indicating that we are making changes to vm or fwd numbers
318 * due to vm provider change.
319 */
320 private boolean mChangingVMorFwdDueToProviderChange = false;
321
322 /**
323 * True if we are in the process of vm & fwd number change and vm has already been changed.
324 * This is used to decide what to do in case of rollback.
325 */
326 private boolean mVMChangeCompletedSuccessfully = false;
327
328 /**
329 * True if we had full or partial failure setting forwarding numbers and so need to roll them
330 * back.
331 */
332 private boolean mFwdChangesRequireRollback = false;
333
334 /**
335 * Id of error msg to display to user once we are done reverting the VM provider to the previous
336 * one.
337 */
338 private int mVMOrFwdSetError = 0;
339
340 /**
341 * Data about discovered voice mail settings providers.
342 * Is populated by querying which activities can handle ACTION_CONFIGURE_VOICEMAIL.
343 * They key in this map is package name + activity name.
344 * We always add an entry for the default provider with a key of empty
345 * string and intent value of null.
346 * @see #initVoiceMailProviders()
347 */
348 private final Map<String, VoiceMailProvider> mVMProvidersData =
349 new HashMap<String, VoiceMailProvider>();
350
351 /** string to hold old voicemail number as it is being updated. */
352 private String mOldVmNumber;
353
354 // New call forwarding settings and vm number we will be setting
355 // Need to save these since before we get to saving we need to asynchronously
356 // query the existing forwarding settings.
357 private CallForwardInfo[] mNewFwdSettings;
358 private String mNewVMNumber;
359
360 private boolean mForeground;
361
362 @Override
363 public void onPause() {
364 super.onPause();
365 mForeground = false;
366 }
367
368 /**
369 * We have to pull current settings from the network for all kinds of
370 * voicemail providers so we can tell whether we have to update them,
371 * so use this bit to keep track of whether we're reading settings for the
372 * default provider and should therefore save them out when done.
373 */
374 private boolean mReadingSettingsForDefaultProvider = false;
375
Tyler Gunnbaee2952014-09-10 16:01:02 -0700376 /**
377 * Used to indicate that the voicemail preference should be shown.
378 */
379 private boolean mShowVoicemailPreference = false;
380
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700381 /*
382 * Click Listeners, handle click based on objects attached to UI.
383 */
384
385 // Click listener for all toggle events
386 @Override
387 public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
388 if (preference == mSubMenuVoicemailSettings) {
389 return true;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700390 } else if (preference == mButtonDTMF) {
391 return true;
392 } else if (preference == mButtonTTY) {
393 return true;
394 } else if (preference == mButtonAutoRetry) {
395 android.provider.Settings.Global.putInt(mPhone.getContext().getContentResolver(),
396 android.provider.Settings.Global.CALL_AUTO_RETRY,
397 mButtonAutoRetry.isChecked() ? 1 : 0);
398 return true;
399 } else if (preference == mButtonHAC) {
400 int hac = mButtonHAC.isChecked() ? 1 : 0;
401 // Update HAC value in Settings database
402 Settings.System.putInt(mPhone.getContext().getContentResolver(),
403 Settings.System.HEARING_AID, hac);
404
405 // Update HAC Value in AudioManager
406 mAudioManager.setParameter(HAC_KEY, hac != 0 ? HAC_VAL_ON : HAC_VAL_OFF);
407 return true;
408 } else if (preference == mVoicemailSettings) {
Yorke Leea0f63bf2014-10-09 18:27:20 -0700409 final Dialog dialog = mVoicemailSettings.getDialog();
410 if (dialog != null) {
411 dialog.getActionBar().setDisplayHomeAsUpEnabled(false);
412 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700413 if (DBG) log("onPreferenceTreeClick: Voicemail Settings Preference is clicked.");
414 if (preference.getIntent() != null) {
415 if (DBG) {
416 log("onPreferenceTreeClick: Invoking cfg intent "
417 + preference.getIntent().getPackage());
418 }
419
420 // onActivityResult() will be responsible for resetting some of variables.
421 this.startActivityForResult(preference.getIntent(), VOICEMAIL_PROVIDER_CFG_ID);
422 return true;
423 } else {
424 if (DBG) {
425 log("onPreferenceTreeClick:"
426 + " No Intent is available. Use default behavior defined in xml.");
427 }
428
429 // There's no onActivityResult(), so we need to take care of some of variables
430 // which should be reset here.
431 mPreviousVMProviderKey = DEFAULT_VM_PROVIDER_KEY;
432 mVMProviderSettingsForced = false;
433
434 // This should let the preference use default behavior in the xml.
435 return false;
436 }
Andrew Lee97708a42014-09-25 12:39:07 -0700437 } else if (preference == mVoicemailSettingsScreen) {
Yorke Leea0f63bf2014-10-09 18:27:20 -0700438 final Dialog dialog = mVoicemailSettingsScreen.getDialog();
439 if (dialog != null) {
440 dialog.getActionBar().setDisplayHomeAsUpEnabled(false);
441 }
Andrew Lee97708a42014-09-25 12:39:07 -0700442 return false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700443 }
444 return false;
445 }
446
447 /**
448 * Implemented to support onPreferenceChangeListener to look for preference
449 * changes.
450 *
451 * @param preference is the preference to be changed
452 * @param objValue should be the value of the selection, NOT its localized
453 * display value.
454 */
455 @Override
456 public boolean onPreferenceChange(Preference preference, Object objValue) {
457 if (DBG) {
Andrew Leedf14ead2014-10-17 14:22:52 -0700458 log("onPreferenceChange(). preference: \"" + preference + "\""
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700459 + ", value: \"" + objValue + "\"");
460 }
Andrew Lee2170a972014-08-13 18:13:01 -0700461
462 if (preference == mButtonDTMF) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700463 int index = mButtonDTMF.findIndexOfValue((String) objValue);
464 Settings.System.putInt(mPhone.getContext().getContentResolver(),
465 Settings.System.DTMF_TONE_TYPE_WHEN_DIALING, index);
466 } else if (preference == mButtonTTY) {
467 handleTTYChange(preference, objValue);
468 } else if (preference == mVoicemailProviders) {
469 final String newProviderKey = (String) objValue;
470 if (DBG) {
471 log("Voicemail Provider changes from \"" + mPreviousVMProviderKey
472 + "\" to \"" + newProviderKey + "\".");
473 }
474 // If previous provider key and the new one is same, we don't need to handle it.
475 if (mPreviousVMProviderKey.equals(newProviderKey)) {
476 if (DBG) log("No change is made toward VM provider setting.");
477 return true;
478 }
479 updateVMPreferenceWidgets(newProviderKey);
480
Andrew Leeb490d732014-10-27 15:00:41 -0700481 final VoicemailProviderSettings newProviderSettings =
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700482 loadSettingsForVoiceMailProvider(newProviderKey);
483
484 // If the user switches to a voice mail provider and we have a
485 // numbers stored for it we will automatically change the
486 // phone's
487 // voice mail and forwarding number to the stored ones.
488 // Otherwise we will bring up provider's configuration UI.
489
490 if (newProviderSettings == null) {
491 // Force the user into a configuration of the chosen provider
492 Log.w(LOG_TAG, "Saved preferences not found - invoking config");
493 mVMProviderSettingsForced = true;
494 simulatePreferenceClick(mVoicemailSettings);
495 } else {
496 if (DBG) log("Saved preferences found - switching to them");
497 // Set this flag so if we get a failure we revert to previous provider
498 mChangingVMorFwdDueToProviderChange = true;
499 saveVoiceMailAndForwardingNumber(newProviderKey, newProviderSettings);
500 }
Andrew Leedf14ead2014-10-17 14:22:52 -0700501 } else if (preference == mEnableVideoCalling) {
502 PhoneGlobals.getInstance().phoneMgr.enableVideoCalling((boolean) objValue);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700503 }
504 // always let the preference setting proceed.
505 return true;
506 }
507
508 @Override
509 public void onDialogClosed(EditPhoneNumberPreference preference, int buttonClicked) {
510 if (DBG) log("onPreferenceClick: request preference click on dialog close: " +
511 buttonClicked);
512 if (buttonClicked == DialogInterface.BUTTON_NEGATIVE) {
513 return;
514 }
515
516 if (preference == mSubMenuVoicemailSettings) {
517 handleVMBtnClickRequest();
518 }
519 }
520
521 /**
522 * Implemented for EditPhoneNumberPreference.GetDefaultNumberListener.
523 * This method set the default values for the various
524 * EditPhoneNumberPreference dialogs.
525 */
526 @Override
527 public String onGetDefaultNumber(EditPhoneNumberPreference preference) {
528 if (preference == mSubMenuVoicemailSettings) {
529 // update the voicemail number field, which takes care of the
530 // mSubMenuVoicemailSettings itself, so we should return null.
531 if (DBG) log("updating default for voicemail dialog");
532 updateVoiceNumberField();
533 return null;
534 }
535
536 String vmDisplay = mPhone.getVoiceMailNumber();
537 if (TextUtils.isEmpty(vmDisplay)) {
538 // if there is no voicemail number, we just return null to
539 // indicate no contribution.
540 return null;
541 }
542
543 // Return the voicemail number prepended with "VM: "
544 if (DBG) log("updating default for call forwarding dialogs");
545 return getString(R.string.voicemail_abbreviated) + " " + vmDisplay;
546 }
547
548
549 // override the startsubactivity call to make changes in state consistent.
550 @Override
551 public void startActivityForResult(Intent intent, int requestCode) {
552 if (requestCode == -1) {
553 // this is an intent requested from the preference framework.
554 super.startActivityForResult(intent, requestCode);
555 return;
556 }
557
558 if (DBG) log("startSubActivity: starting requested subactivity");
559 super.startActivityForResult(intent, requestCode);
560 }
561
562 private void switchToPreviousVoicemailProvider() {
563 if (DBG) log("switchToPreviousVoicemailProvider " + mPreviousVMProviderKey);
564 if (mPreviousVMProviderKey != null) {
565 if (mVMChangeCompletedSuccessfully || mFwdChangesRequireRollback) {
566 // we have to revert with carrier
567 if (DBG) {
568 log("Needs to rollback."
569 + " mVMChangeCompletedSuccessfully=" + mVMChangeCompletedSuccessfully
570 + ", mFwdChangesRequireRollback=" + mFwdChangesRequireRollback);
571 }
572
573 showDialogIfForeground(VOICEMAIL_REVERTING_DIALOG);
Andrew Leeb490d732014-10-27 15:00:41 -0700574 final VoicemailProviderSettings prevSettings =
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700575 loadSettingsForVoiceMailProvider(mPreviousVMProviderKey);
576 if (prevSettings == null) {
577 // prevSettings never becomes null since it should be already loaded!
Andrew Leeb490d732014-10-27 15:00:41 -0700578 Log.e(LOG_TAG, "VoicemailProviderSettings for the key \""
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700579 + mPreviousVMProviderKey + "\" becomes null, which is unexpected.");
580 if (DBG) {
581 Log.e(LOG_TAG,
582 "mVMChangeCompletedSuccessfully: " + mVMChangeCompletedSuccessfully
583 + ", mFwdChangesRequireRollback: " + mFwdChangesRequireRollback);
584 }
585 }
586 if (mVMChangeCompletedSuccessfully) {
Andrew Leeb490d732014-10-27 15:00:41 -0700587 mNewVMNumber = prevSettings.getVoicemailNumber();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700588 Log.i(LOG_TAG, "VM change is already completed successfully."
589 + "Have to revert VM back to " + mNewVMNumber + " again.");
590 mPhone.setVoiceMailNumber(
591 mPhone.getVoiceMailAlphaTag().toString(),
592 mNewVMNumber,
593 Message.obtain(mRevertOptionComplete, EVENT_VOICEMAIL_CHANGED));
594 }
595 if (mFwdChangesRequireRollback) {
596 Log.i(LOG_TAG, "Requested to rollback Fwd changes.");
Andrew Leeb490d732014-10-27 15:00:41 -0700597 final CallForwardInfo[] prevFwdSettings = prevSettings.getForwardingSettings();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700598 if (prevFwdSettings != null) {
599 Map<Integer, AsyncResult> results =
600 mForwardingChangeResults;
601 resetForwardingChangeState();
602 for (int i = 0; i < prevFwdSettings.length; i++) {
603 CallForwardInfo fi = prevFwdSettings[i];
604 if (DBG) log("Reverting fwd #: " + i + ": " + fi.toString());
605 // Only revert the settings for which the update
606 // succeeded
607 AsyncResult result = results.get(fi.reason);
608 if (result != null && result.exception == null) {
609 mExpectedChangeResultReasons.add(fi.reason);
610 mPhone.setCallForwardingOption(
611 (fi.status == 1 ?
612 CommandsInterface.CF_ACTION_REGISTRATION :
613 CommandsInterface.CF_ACTION_DISABLE),
614 fi.reason,
615 fi.number,
616 fi.timeSeconds,
617 mRevertOptionComplete.obtainMessage(
618 EVENT_FORWARDING_CHANGED, i, 0));
619 }
620 }
621 }
622 }
623 } else {
624 if (DBG) log("No need to revert");
625 onRevertDone();
626 }
627 }
628 }
629
630 private void onRevertDone() {
631 if (DBG) log("Flipping provider key back to " + mPreviousVMProviderKey);
632 mVoicemailProviders.setValue(mPreviousVMProviderKey);
633 updateVMPreferenceWidgets(mPreviousVMProviderKey);
634 updateVoiceNumberField();
635 if (mVMOrFwdSetError != 0) {
636 showVMDialog(mVMOrFwdSetError);
637 mVMOrFwdSetError = 0;
638 }
639 }
640
641 @Override
642 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
643 if (DBG) {
644 log("onActivityResult: requestCode: " + requestCode
645 + ", resultCode: " + resultCode
646 + ", data: " + data);
647 }
648 // there are cases where the contact picker may end up sending us more than one
649 // request. We want to ignore the request if we're not in the correct state.
650 if (requestCode == VOICEMAIL_PROVIDER_CFG_ID) {
651 boolean failure = false;
652
653 // No matter how the processing of result goes lets clear the flag
654 if (DBG) log("mVMProviderSettingsForced: " + mVMProviderSettingsForced);
655 final boolean isVMProviderSettingsForced = mVMProviderSettingsForced;
656 mVMProviderSettingsForced = false;
657
658 String vmNum = null;
659 if (resultCode != RESULT_OK) {
660 if (DBG) log("onActivityResult: vm provider cfg result not OK.");
661 failure = true;
662 } else {
663 if (data == null) {
664 if (DBG) log("onActivityResult: vm provider cfg result has no data");
665 failure = true;
666 } else {
667 if (data.getBooleanExtra(SIGNOUT_EXTRA, false)) {
668 if (DBG) log("Provider requested signout");
669 if (isVMProviderSettingsForced) {
670 if (DBG) log("Going back to previous provider on signout");
671 switchToPreviousVoicemailProvider();
672 } else {
673 final String victim = getCurrentVoicemailProviderKey();
674 if (DBG) log("Relaunching activity and ignoring " + victim);
675 Intent i = new Intent(ACTION_ADD_VOICEMAIL);
676 i.putExtra(IGNORE_PROVIDER_EXTRA, victim);
677 i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
678 this.startActivity(i);
679 }
680 return;
681 }
682 vmNum = data.getStringExtra(VM_NUMBER_EXTRA);
683 if (vmNum == null || vmNum.length() == 0) {
684 if (DBG) log("onActivityResult: vm provider cfg result has no vmnum");
685 failure = true;
686 }
687 }
688 }
689 if (failure) {
690 if (DBG) log("Failure in return from voicemail provider");
691 if (isVMProviderSettingsForced) {
692 switchToPreviousVoicemailProvider();
693 } else {
694 if (DBG) log("Not switching back the provider since this is not forced config");
695 }
696 return;
697 }
698 mChangingVMorFwdDueToProviderChange = isVMProviderSettingsForced;
699 final String fwdNum = data.getStringExtra(FWD_NUMBER_EXTRA);
700
Santos Cordonda120f42014-08-06 04:44:34 -0700701 // TODO: It would be nice to load the current network setting for this and
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700702 // send it to the provider when it's config is invoked so it can use this as default
703 final int fwdNumTime = data.getIntExtra(FWD_NUMBER_TIME_EXTRA, 20);
704
705 if (DBG) log("onActivityResult: vm provider cfg result " +
706 (fwdNum != null ? "has" : " does not have") + " forwarding number");
707 saveVoiceMailAndForwardingNumber(getCurrentVoicemailProviderKey(),
Andrew Leeb490d732014-10-27 15:00:41 -0700708 new VoicemailProviderSettings(vmNum, fwdNum, fwdNumTime));
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700709 return;
710 }
711
712 if (requestCode == VOICEMAIL_PREF_ID) {
713 if (resultCode != RESULT_OK) {
714 if (DBG) log("onActivityResult: contact picker result not OK.");
715 return;
716 }
717
718 Cursor cursor = null;
719 try {
720 cursor = getContentResolver().query(data.getData(),
721 NUM_PROJECTION, null, null, null);
722 if ((cursor == null) || (!cursor.moveToFirst())) {
723 if (DBG) log("onActivityResult: bad contact data, no results found.");
724 return;
725 }
726 mSubMenuVoicemailSettings.onPickActivityResult(cursor.getString(0));
727 return;
728 } finally {
729 if (cursor != null) {
730 cursor.close();
731 }
732 }
733 }
734
735 super.onActivityResult(requestCode, resultCode, data);
736 }
737
738 // Voicemail button logic
739 private void handleVMBtnClickRequest() {
740 // normally called on the dialog close.
741
742 // Since we're stripping the formatting out on the getPhoneNumber()
743 // call now, we won't need to do so here anymore.
744
745 saveVoiceMailAndForwardingNumber(
746 getCurrentVoicemailProviderKey(),
Andrew Leeb490d732014-10-27 15:00:41 -0700747 new VoicemailProviderSettings(mSubMenuVoicemailSettings.getPhoneNumber(),
748 VoicemailProviderSettings.NO_FORWARDING)
Tyler Gunn4d45d1c2014-09-12 22:17:53 -0700749 );
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700750 }
751
752
753 /**
754 * Wrapper around showDialog() that will silently do nothing if we're
755 * not in the foreground.
756 *
757 * This is useful here because most of the dialogs we display from
758 * this class are triggered by asynchronous events (like
759 * success/failure messages from the telephony layer) and it's
760 * possible for those events to come in even after the user has gone
761 * to a different screen.
762 */
763 // TODO: this is too brittle: it's still easy to accidentally add new
764 // code here that calls showDialog() directly (which will result in a
765 // WindowManager$BadTokenException if called after the activity has
766 // been stopped.)
767 //
768 // It would be cleaner to do the "if (mForeground)" check in one
769 // central place, maybe by using a single Handler for all asynchronous
770 // events (and have *that* discard events if we're not in the
771 // foreground.)
772 //
773 // Unfortunately it's not that simple, since we sometimes need to do
774 // actual work to handle these events whether or not we're in the
775 // foreground (see the Handler code in mSetOptionComplete for
776 // example.)
777 private void showDialogIfForeground(int id) {
778 if (mForeground) {
779 showDialog(id);
780 }
781 }
782
783 private void dismissDialogSafely(int id) {
784 try {
785 dismissDialog(id);
786 } catch (IllegalArgumentException e) {
787 // This is expected in the case where we were in the background
788 // at the time we would normally have shown the dialog, so we didn't
789 // show it.
790 }
791 }
792
Andrew Leeb490d732014-10-27 15:00:41 -0700793 private void saveVoiceMailAndForwardingNumber(
794 String key, VoicemailProviderSettings newSettings) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700795 if (DBG) log("saveVoiceMailAndForwardingNumber: " + newSettings.toString());
Andrew Leeb490d732014-10-27 15:00:41 -0700796 mNewVMNumber = newSettings.getVoicemailNumber();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700797 // empty vm number == clearing the vm number ?
798 if (mNewVMNumber == null) {
799 mNewVMNumber = "";
800 }
801
Andrew Leeb490d732014-10-27 15:00:41 -0700802 mNewFwdSettings = newSettings.getForwardingSettings();
803 if (DBG) log("newFwdNumber "
804 + String.valueOf((mNewFwdSettings != null ? mNewFwdSettings.length : 0))
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700805 + " settings");
806
807 // No fwd settings on CDMA
808 if (mPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
809 if (DBG) log("ignoring forwarding setting since this is CDMA phone");
Andrew Leeb490d732014-10-27 15:00:41 -0700810 mNewFwdSettings = VoicemailProviderSettings.NO_FORWARDING;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700811 }
812
Andrew Leeb490d732014-10-27 15:00:41 -0700813 //Throw a warning if the voicemail is the same and we did not change forwarding.
814 if (mNewVMNumber.equals(mOldVmNumber)
815 && mNewFwdSettings == VoicemailProviderSettings.NO_FORWARDING) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700816 showVMDialog(MSG_VM_NOCHANGE);
817 return;
818 }
819
820 maybeSaveSettingsForVoicemailProvider(key, newSettings);
821 mVMChangeCompletedSuccessfully = false;
822 mFwdChangesRequireRollback = false;
823 mVMOrFwdSetError = 0;
824 if (!key.equals(mPreviousVMProviderKey)) {
825 mReadingSettingsForDefaultProvider =
826 mPreviousVMProviderKey.equals(DEFAULT_VM_PROVIDER_KEY);
827 if (DBG) log("Reading current forwarding settings");
Andrew Leeb490d732014-10-27 15:00:41 -0700828 int numSettingsReasons = VoicemailProviderSettings.FORWARDING_SETTINGS_REASONS.length;
829 mForwardingReadResults = new CallForwardInfo[numSettingsReasons];
830 for (int i = 0; i < mForwardingReadResults.length; i++) {
831 mPhone.getCallForwardingOption(
832 VoicemailProviderSettings.FORWARDING_SETTINGS_REASONS[i],
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700833 mGetOptionComplete.obtainMessage(EVENT_FORWARDING_GET_COMPLETED, i, 0));
834 }
835 showDialogIfForeground(VOICEMAIL_FWD_READING_DIALOG);
836 } else {
837 saveVoiceMailAndForwardingNumberStage2();
838 }
839 }
840
841 private final Handler mGetOptionComplete = new Handler() {
842 @Override
843 public void handleMessage(Message msg) {
844 AsyncResult result = (AsyncResult) msg.obj;
845 switch (msg.what) {
846 case EVENT_FORWARDING_GET_COMPLETED:
847 handleForwardingSettingsReadResult(result, msg.arg1);
848 break;
849 }
850 }
851 };
852
853 private void handleForwardingSettingsReadResult(AsyncResult ar, int idx) {
854 if (DBG) Log.d(LOG_TAG, "handleForwardingSettingsReadResult: " + idx);
855 Throwable error = null;
856 if (ar.exception != null) {
857 if (DBG) Log.d(LOG_TAG, "FwdRead: ar.exception=" +
858 ar.exception.getMessage());
859 error = ar.exception;
860 }
861 if (ar.userObj instanceof Throwable) {
862 if (DBG) Log.d(LOG_TAG, "FwdRead: userObj=" +
863 ((Throwable)ar.userObj).getMessage());
864 error = (Throwable)ar.userObj;
865 }
866
867 // We may have already gotten an error and decided to ignore the other results.
868 if (mForwardingReadResults == null) {
869 if (DBG) Log.d(LOG_TAG, "ignoring fwd reading result: " + idx);
870 return;
871 }
872
873 // In case of error ignore other results, show an error dialog
874 if (error != null) {
875 if (DBG) Log.d(LOG_TAG, "Error discovered for fwd read : " + idx);
876 mForwardingReadResults = null;
877 dismissDialogSafely(VOICEMAIL_FWD_READING_DIALOG);
878 showVMDialog(MSG_FW_GET_EXCEPTION);
879 return;
880 }
881
882 // Get the forwarding info
883 final CallForwardInfo cfInfoArray[] = (CallForwardInfo[]) ar.result;
884 CallForwardInfo fi = null;
885 for (int i = 0 ; i < cfInfoArray.length; i++) {
886 if ((cfInfoArray[i].serviceClass & CommandsInterface.SERVICE_CLASS_VOICE) != 0) {
887 fi = cfInfoArray[i];
888 break;
889 }
890 }
891 if (fi == null) {
892
893 // In case we go nothing it means we need this reason disabled
894 // so create a CallForwardInfo for capturing this
895 if (DBG) Log.d(LOG_TAG, "Creating default info for " + idx);
896 fi = new CallForwardInfo();
897 fi.status = 0;
Andrew Leeb490d732014-10-27 15:00:41 -0700898 fi.reason = VoicemailProviderSettings.FORWARDING_SETTINGS_REASONS[idx];
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700899 fi.serviceClass = CommandsInterface.SERVICE_CLASS_VOICE;
900 } else {
901 // if there is not a forwarding number, ensure the entry is set to "not active."
902 if (fi.number == null || fi.number.length() == 0) {
903 fi.status = 0;
904 }
905
906 if (DBG) Log.d(LOG_TAG, "Got " + fi.toString() + " for " + idx);
907 }
908 mForwardingReadResults[idx] = fi;
909
910 // Check if we got all the results already
911 boolean done = true;
912 for (int i = 0; i < mForwardingReadResults.length; i++) {
913 if (mForwardingReadResults[i] == null) {
914 done = false;
915 break;
916 }
917 }
918 if (done) {
919 if (DBG) Log.d(LOG_TAG, "Done receiving fwd info");
920 dismissDialogSafely(VOICEMAIL_FWD_READING_DIALOG);
921 if (mReadingSettingsForDefaultProvider) {
922 maybeSaveSettingsForVoicemailProvider(DEFAULT_VM_PROVIDER_KEY,
Andrew Leeb490d732014-10-27 15:00:41 -0700923 new VoicemailProviderSettings(this.mOldVmNumber,
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700924 mForwardingReadResults));
925 mReadingSettingsForDefaultProvider = false;
926 }
927 saveVoiceMailAndForwardingNumberStage2();
928 } else {
929 if (DBG) Log.d(LOG_TAG, "Not done receiving fwd info");
930 }
931 }
932
933 private CallForwardInfo infoForReason(CallForwardInfo[] infos, int reason) {
934 CallForwardInfo result = null;
935 if (null != infos) {
936 for (CallForwardInfo info : infos) {
937 if (info.reason == reason) {
938 result = info;
939 break;
940 }
941 }
942 }
943 return result;
944 }
945
946 private boolean isUpdateRequired(CallForwardInfo oldInfo,
947 CallForwardInfo newInfo) {
948 boolean result = true;
949 if (0 == newInfo.status) {
950 // If we're disabling a type of forwarding, and it's already
951 // disabled for the account, don't make any change
952 if (oldInfo != null && oldInfo.status == 0) {
953 result = false;
954 }
955 }
956 return result;
957 }
958
959 private void resetForwardingChangeState() {
960 mForwardingChangeResults = new HashMap<Integer, AsyncResult>();
961 mExpectedChangeResultReasons = new HashSet<Integer>();
962 }
963
964 // Called after we are done saving the previous forwarding settings if
965 // we needed.
966 private void saveVoiceMailAndForwardingNumberStage2() {
967 mForwardingChangeResults = null;
968 mVoicemailChangeResult = null;
Andrew Leeb490d732014-10-27 15:00:41 -0700969 if (mNewFwdSettings != VoicemailProviderSettings.NO_FORWARDING) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700970 resetForwardingChangeState();
971 for (int i = 0; i < mNewFwdSettings.length; i++) {
972 CallForwardInfo fi = mNewFwdSettings[i];
973
974 final boolean doUpdate = isUpdateRequired(infoForReason(
975 mForwardingReadResults, fi.reason), fi);
976
977 if (doUpdate) {
978 if (DBG) log("Setting fwd #: " + i + ": " + fi.toString());
979 mExpectedChangeResultReasons.add(i);
980
981 mPhone.setCallForwardingOption(
982 fi.status == 1 ?
983 CommandsInterface.CF_ACTION_REGISTRATION :
984 CommandsInterface.CF_ACTION_DISABLE,
985 fi.reason,
986 fi.number,
987 fi.timeSeconds,
988 mSetOptionComplete.obtainMessage(
989 EVENT_FORWARDING_CHANGED, fi.reason, 0));
990 }
991 }
992 showDialogIfForeground(VOICEMAIL_FWD_SAVING_DIALOG);
993 } else {
994 if (DBG) log("Not touching fwd #");
995 setVMNumberWithCarrier();
996 }
997 }
998
999 private void setVMNumberWithCarrier() {
1000 if (DBG) log("save voicemail #: " + mNewVMNumber);
1001 mPhone.setVoiceMailNumber(
1002 mPhone.getVoiceMailAlphaTag().toString(),
1003 mNewVMNumber,
1004 Message.obtain(mSetOptionComplete, EVENT_VOICEMAIL_CHANGED));
1005 }
1006
1007 /**
1008 * Callback to handle option update completions
1009 */
1010 private final Handler mSetOptionComplete = new Handler() {
1011 @Override
1012 public void handleMessage(Message msg) {
1013 AsyncResult result = (AsyncResult) msg.obj;
1014 boolean done = false;
1015 switch (msg.what) {
1016 case EVENT_VOICEMAIL_CHANGED:
1017 mVoicemailChangeResult = result;
1018 mVMChangeCompletedSuccessfully = checkVMChangeSuccess() == null;
1019 if (DBG) log("VM change complete msg, VM change done = " +
1020 String.valueOf(mVMChangeCompletedSuccessfully));
1021 done = true;
1022 break;
1023 case EVENT_FORWARDING_CHANGED:
1024 mForwardingChangeResults.put(msg.arg1, result);
1025 if (result.exception != null) {
1026 Log.w(LOG_TAG, "Error in setting fwd# " + msg.arg1 + ": " +
1027 result.exception.getMessage());
1028 } else {
1029 if (DBG) log("Success in setting fwd# " + msg.arg1);
1030 }
1031 final boolean completed = checkForwardingCompleted();
1032 if (completed) {
1033 if (checkFwdChangeSuccess() == null) {
1034 if (DBG) log("Overall fwd changes completed ok, starting vm change");
1035 setVMNumberWithCarrier();
1036 } else {
1037 Log.w(LOG_TAG, "Overall fwd changes completed in failure. " +
1038 "Check if we need to try rollback for some settings.");
1039 mFwdChangesRequireRollback = false;
1040 Iterator<Map.Entry<Integer,AsyncResult>> it =
1041 mForwardingChangeResults.entrySet().iterator();
1042 while (it.hasNext()) {
1043 Map.Entry<Integer,AsyncResult> entry = it.next();
1044 if (entry.getValue().exception == null) {
1045 // If at least one succeeded we have to revert
1046 Log.i(LOG_TAG, "Rollback will be required");
1047 mFwdChangesRequireRollback = true;
1048 break;
1049 }
1050 }
1051 if (!mFwdChangesRequireRollback) {
1052 Log.i(LOG_TAG, "No rollback needed.");
1053 }
1054 done = true;
1055 }
1056 }
1057 break;
1058 default:
1059 // TODO: should never reach this, may want to throw exception
1060 }
1061 if (done) {
1062 if (DBG) log("All VM provider related changes done");
1063 if (mForwardingChangeResults != null) {
1064 dismissDialogSafely(VOICEMAIL_FWD_SAVING_DIALOG);
1065 }
1066 handleSetVMOrFwdMessage();
1067 }
1068 }
1069 };
1070
1071 /**
1072 * Callback to handle option revert completions
1073 */
1074 private final Handler mRevertOptionComplete = new Handler() {
1075 @Override
1076 public void handleMessage(Message msg) {
1077 AsyncResult result = (AsyncResult) msg.obj;
1078 switch (msg.what) {
1079 case EVENT_VOICEMAIL_CHANGED:
1080 mVoicemailChangeResult = result;
1081 if (DBG) log("VM revert complete msg");
1082 break;
1083 case EVENT_FORWARDING_CHANGED:
1084 mForwardingChangeResults.put(msg.arg1, result);
1085 if (result.exception != null) {
1086 if (DBG) log("Error in reverting fwd# " + msg.arg1 + ": " +
1087 result.exception.getMessage());
1088 } else {
1089 if (DBG) log("Success in reverting fwd# " + msg.arg1);
1090 }
1091 if (DBG) log("FWD revert complete msg ");
1092 break;
1093 default:
1094 // TODO: should never reach this, may want to throw exception
1095 }
1096 final boolean done =
1097 (!mVMChangeCompletedSuccessfully || mVoicemailChangeResult != null) &&
1098 (!mFwdChangesRequireRollback || checkForwardingCompleted());
1099 if (done) {
1100 if (DBG) log("All VM reverts done");
1101 dismissDialogSafely(VOICEMAIL_REVERTING_DIALOG);
1102 onRevertDone();
1103 }
1104 }
1105 };
1106
1107 /**
1108 * @return true if forwarding change has completed
1109 */
1110 private boolean checkForwardingCompleted() {
1111 boolean result;
1112 if (mForwardingChangeResults == null) {
1113 result = true;
1114 } else {
1115 // return true iff there is a change result for every reason for
1116 // which we expected a result
1117 result = true;
1118 for (Integer reason : mExpectedChangeResultReasons) {
1119 if (mForwardingChangeResults.get(reason) == null) {
1120 result = false;
1121 break;
1122 }
1123 }
1124 }
1125 return result;
1126 }
1127 /**
1128 * @return error string or null if successful
1129 */
1130 private String checkFwdChangeSuccess() {
1131 String result = null;
1132 Iterator<Map.Entry<Integer,AsyncResult>> it =
1133 mForwardingChangeResults.entrySet().iterator();
1134 while (it.hasNext()) {
1135 Map.Entry<Integer,AsyncResult> entry = it.next();
1136 Throwable exception = entry.getValue().exception;
1137 if (exception != null) {
1138 result = exception.getMessage();
1139 if (result == null) {
1140 result = "";
1141 }
1142 break;
1143 }
1144 }
1145 return result;
1146 }
1147
1148 /**
1149 * @return error string or null if successful
1150 */
1151 private String checkVMChangeSuccess() {
1152 if (mVoicemailChangeResult.exception != null) {
1153 final String msg = mVoicemailChangeResult.exception.getMessage();
1154 if (msg == null) {
1155 return "";
1156 }
1157 return msg;
1158 }
1159 return null;
1160 }
1161
1162 private void handleSetVMOrFwdMessage() {
1163 if (DBG) {
1164 log("handleSetVMMessage: set VM request complete");
1165 }
1166 boolean success = true;
1167 boolean fwdFailure = false;
1168 String exceptionMessage = "";
1169 if (mForwardingChangeResults != null) {
1170 exceptionMessage = checkFwdChangeSuccess();
1171 if (exceptionMessage != null) {
1172 success = false;
1173 fwdFailure = true;
1174 }
1175 }
1176 if (success) {
1177 exceptionMessage = checkVMChangeSuccess();
1178 if (exceptionMessage != null) {
1179 success = false;
1180 }
1181 }
1182 if (success) {
1183 if (DBG) log("change VM success!");
1184 handleVMAndFwdSetSuccess(MSG_VM_OK);
1185 } else {
1186 if (fwdFailure) {
1187 Log.w(LOG_TAG, "Failed to change fowarding setting. Reason: " + exceptionMessage);
1188 handleVMOrFwdSetError(MSG_FW_SET_EXCEPTION);
1189 } else {
1190 Log.w(LOG_TAG, "Failed to change voicemail. Reason: " + exceptionMessage);
1191 handleVMOrFwdSetError(MSG_VM_EXCEPTION);
1192 }
1193 }
1194 }
1195
1196 /**
1197 * Called when Voicemail Provider or its forwarding settings failed. Rolls back partly made
1198 * changes to those settings and show "failure" dialog.
1199 *
1200 * @param msgId Message ID used for the specific error case. {@link #MSG_FW_SET_EXCEPTION} or
1201 * {@link #MSG_VM_EXCEPTION}
1202 */
1203 private void handleVMOrFwdSetError(int msgId) {
1204 if (mChangingVMorFwdDueToProviderChange) {
1205 mVMOrFwdSetError = msgId;
1206 mChangingVMorFwdDueToProviderChange = false;
1207 switchToPreviousVoicemailProvider();
1208 return;
1209 }
1210 mChangingVMorFwdDueToProviderChange = false;
1211 showVMDialog(msgId);
1212 updateVoiceNumberField();
1213 }
1214
1215 /**
1216 * Called when Voicemail Provider and its forwarding settings were successfully finished.
1217 * This updates a bunch of variables and show "success" dialog.
1218 */
1219 private void handleVMAndFwdSetSuccess(int msg) {
1220 if (DBG) {
1221 log("handleVMAndFwdSetSuccess(). current voicemail provider key: "
1222 + getCurrentVoicemailProviderKey());
1223 }
1224 mPreviousVMProviderKey = getCurrentVoicemailProviderKey();
1225 mChangingVMorFwdDueToProviderChange = false;
1226 showVMDialog(msg);
1227 updateVoiceNumberField();
1228 }
1229
1230 /**
1231 * Update the voicemail number from what we've recorded on the sim.
1232 */
1233 private void updateVoiceNumberField() {
1234 if (DBG) {
1235 log("updateVoiceNumberField(). mSubMenuVoicemailSettings=" + mSubMenuVoicemailSettings);
1236 }
1237 if (mSubMenuVoicemailSettings == null) {
1238 return;
1239 }
1240
1241 mOldVmNumber = mPhone.getVoiceMailNumber();
1242 if (mOldVmNumber == null) {
1243 mOldVmNumber = "";
1244 }
1245 mSubMenuVoicemailSettings.setPhoneNumber(mOldVmNumber);
1246 final String summary = (mOldVmNumber.length() > 0) ? mOldVmNumber :
1247 getString(R.string.voicemail_number_not_set);
1248 mSubMenuVoicemailSettings.setSummary(summary);
1249 }
1250
1251 /*
1252 * Helper Methods for Activity class.
1253 * The initial query commands are split into two pieces now
1254 * for individual expansion. This combined with the ability
1255 * to cancel queries allows for a much better user experience,
1256 * and also ensures that the user only waits to update the
1257 * data that is relevant.
1258 */
1259
1260 @Override
1261 protected void onPrepareDialog(int id, Dialog dialog) {
1262 super.onPrepareDialog(id, dialog);
1263 mCurrentDialogId = id;
1264 }
1265
1266 // dialog creation method, called by showDialog()
1267 @Override
1268 protected Dialog onCreateDialog(int id) {
1269 if ((id == VM_RESPONSE_ERROR) || (id == VM_NOCHANGE_ERROR) ||
1270 (id == FW_SET_RESPONSE_ERROR) || (id == FW_GET_RESPONSE_ERROR) ||
1271 (id == VOICEMAIL_DIALOG_CONFIRM)) {
1272
1273 AlertDialog.Builder b = new AlertDialog.Builder(this);
1274
1275 int msgId;
1276 int titleId = R.string.error_updating_title;
1277 switch (id) {
1278 case VOICEMAIL_DIALOG_CONFIRM:
1279 msgId = R.string.vm_changed;
1280 titleId = R.string.voicemail;
1281 // Set Button 2
1282 b.setNegativeButton(R.string.close_dialog, this);
1283 break;
1284 case VM_NOCHANGE_ERROR:
1285 // even though this is technically an error,
1286 // keep the title friendly.
1287 msgId = R.string.no_change;
1288 titleId = R.string.voicemail;
1289 // Set Button 2
1290 b.setNegativeButton(R.string.close_dialog, this);
1291 break;
1292 case VM_RESPONSE_ERROR:
1293 msgId = R.string.vm_change_failed;
1294 // Set Button 1
1295 b.setPositiveButton(R.string.close_dialog, this);
1296 break;
1297 case FW_SET_RESPONSE_ERROR:
1298 msgId = R.string.fw_change_failed;
1299 // Set Button 1
1300 b.setPositiveButton(R.string.close_dialog, this);
1301 break;
1302 case FW_GET_RESPONSE_ERROR:
1303 msgId = R.string.fw_get_in_vm_failed;
1304 b.setPositiveButton(R.string.alert_dialog_yes, this);
1305 b.setNegativeButton(R.string.alert_dialog_no, this);
1306 break;
1307 default:
1308 msgId = R.string.exception_error;
1309 // Set Button 3, tells the activity that the error is
1310 // not recoverable on dialog exit.
1311 b.setNeutralButton(R.string.close_dialog, this);
1312 break;
1313 }
1314
1315 b.setTitle(getText(titleId));
1316 String message = getText(msgId).toString();
1317 b.setMessage(message);
1318 b.setCancelable(false);
1319 AlertDialog dialog = b.create();
1320
1321 // make the dialog more obvious by bluring the background.
1322 dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
1323
1324 return dialog;
1325 } else if (id == VOICEMAIL_FWD_SAVING_DIALOG || id == VOICEMAIL_FWD_READING_DIALOG ||
1326 id == VOICEMAIL_REVERTING_DIALOG) {
1327 ProgressDialog dialog = new ProgressDialog(this);
1328 dialog.setTitle(getText(R.string.updating_title));
1329 dialog.setIndeterminate(true);
1330 dialog.setCancelable(false);
1331 dialog.setMessage(getText(
1332 id == VOICEMAIL_FWD_SAVING_DIALOG ? R.string.updating_settings :
1333 (id == VOICEMAIL_REVERTING_DIALOG ? R.string.reverting_settings :
1334 R.string.reading_settings)));
1335 return dialog;
1336 }
1337
1338
1339 return null;
1340 }
1341
1342 // This is a method implemented for DialogInterface.OnClickListener.
1343 // Used with the error dialog to close the app, voicemail dialog to just dismiss.
1344 // Close button is mapped to BUTTON_POSITIVE for the errors that close the activity,
1345 // while those that are mapped to BUTTON_NEUTRAL only move the preference focus.
1346 public void onClick(DialogInterface dialog, int which) {
1347 dialog.dismiss();
1348 switch (which){
1349 case DialogInterface.BUTTON_NEUTRAL:
1350 if (DBG) log("Neutral button");
1351 break;
1352 case DialogInterface.BUTTON_NEGATIVE:
1353 if (DBG) log("Negative button");
1354 if (mCurrentDialogId == FW_GET_RESPONSE_ERROR) {
1355 // We failed to get current forwarding settings and the user
1356 // does not wish to continue.
1357 switchToPreviousVoicemailProvider();
1358 }
1359 break;
1360 case DialogInterface.BUTTON_POSITIVE:
1361 if (DBG) log("Positive button");
1362 if (mCurrentDialogId == FW_GET_RESPONSE_ERROR) {
1363 // We failed to get current forwarding settings but the user
1364 // wishes to continue changing settings to the new vm provider
1365 saveVoiceMailAndForwardingNumberStage2();
1366 } else {
1367 finish();
1368 }
1369 return;
1370 default:
1371 // just let the dialog close and go back to the input
1372 }
1373 // In all dialogs, all buttons except BUTTON_POSITIVE lead to the end of user interaction
1374 // with settings UI. If we were called to explicitly configure voice mail then
1375 // we finish the settings activity here to come back to whatever the user was doing.
1376 if (getIntent().getAction().equals(ACTION_ADD_VOICEMAIL)) {
1377 finish();
1378 }
1379 }
1380
1381 // set the app state with optional status.
1382 private void showVMDialog(int msgStatus) {
1383 switch (msgStatus) {
1384 // It's a bit worrisome to punt in the error cases here when we're
1385 // not in the foreground; maybe toast instead?
1386 case MSG_VM_EXCEPTION:
1387 showDialogIfForeground(VM_RESPONSE_ERROR);
1388 break;
1389 case MSG_FW_SET_EXCEPTION:
1390 showDialogIfForeground(FW_SET_RESPONSE_ERROR);
1391 break;
1392 case MSG_FW_GET_EXCEPTION:
1393 showDialogIfForeground(FW_GET_RESPONSE_ERROR);
1394 break;
1395 case MSG_VM_NOCHANGE:
1396 showDialogIfForeground(VM_NOCHANGE_ERROR);
1397 break;
1398 case MSG_VM_OK:
1399 showDialogIfForeground(VOICEMAIL_DIALOG_CONFIRM);
1400 break;
1401 case MSG_OK:
1402 default:
1403 // This should never happen.
1404 }
1405 }
1406
1407 /*
1408 * Activity class methods
1409 */
1410
1411 @Override
1412 protected void onCreate(Bundle icicle) {
1413 super.onCreate(icicle);
1414 if (DBG) log("onCreate(). Intent: " + getIntent());
1415 mPhone = PhoneGlobals.getPhone();
Tyler Gunnbaee2952014-09-10 16:01:02 -07001416 mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
1417
1418 // create intent to bring up contact list
1419 mContactListIntent = new Intent(Intent.ACTION_GET_CONTENT);
1420 mContactListIntent.setType(android.provider.Contacts.Phones.CONTENT_ITEM_TYPE);
1421
1422 mVoicemailRingtoneLookupRunnable = new Runnable() {
1423 @Override
1424 public void run() {
1425 if (mVoicemailNotificationRingtone != null) {
1426 SettingsUtil.updateRingtoneName(
1427 mPhone.getContext(),
1428 mVoicemailRingtoneLookupComplete,
1429 RingtoneManager.TYPE_NOTIFICATION,
1430 mVoicemailNotificationRingtone,
1431 MSG_UPDATE_VOICEMAIL_RINGTONE_SUMMARY);
1432 }
1433 }
1434 };
1435
Tyler Gunnbaee2952014-09-10 16:01:02 -07001436 // Show the voicemail preference in onResume if the calling intent specifies the
1437 // ACTION_ADD_VOICEMAIL action.
1438 mShowVoicemailPreference = (icicle == null) &&
1439 getIntent().getAction().equals(ACTION_ADD_VOICEMAIL);
1440 }
1441
1442 private void initPhoneAccountPreferences() {
Andrew Leece8ae2a2014-09-10 10:41:48 -07001443 mPhoneAccountSettingsPreference = findPreference(PHONE_ACCOUNT_SETTINGS_KEY);
Tyler Gunnbaee2952014-09-10 16:01:02 -07001444
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001445 TelecomManager telecomManager = TelecomManager.from(this);
Andrew Lee93c345f2014-10-27 15:25:07 -07001446 TelephonyManager telephonyManager =
1447 (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
Tyler Gunnbaee2952014-09-10 16:01:02 -07001448
Andrew Lee93c345f2014-10-27 15:25:07 -07001449 if ((telecomManager.getSimCallManagers().isEmpty() && !SipUtil.isVoipSupported(this))
1450 || telephonyManager.getPhoneCount() > 1) {
Andrew Leece8ae2a2014-09-10 10:41:48 -07001451 getPreferenceScreen().removePreference(mPhoneAccountSettingsPreference);
Tyler Gunnbaee2952014-09-10 16:01:02 -07001452 }
1453 }
1454
1455 private boolean canLaunchIntent(Intent intent) {
1456 PackageManager pm = getPackageManager();
1457 return pm.resolveActivity(intent, PackageManager.GET_ACTIVITIES) != null;
1458 }
1459
Tyler Gunnbaee2952014-09-10 16:01:02 -07001460 @Override
1461 protected void onResume() {
1462 super.onResume();
1463 mForeground = true;
1464
1465 PreferenceScreen preferenceScreen = getPreferenceScreen();
1466 if (preferenceScreen != null) {
1467 preferenceScreen.removeAll();
1468 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001469
1470 addPreferencesFromResource(R.xml.call_feature_setting);
Andrew Leedb2fe562014-09-03 15:40:43 -07001471 initPhoneAccountPreferences();
1472
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001473 // get buttons
1474 PreferenceScreen prefSet = getPreferenceScreen();
Andrew Lee64a7d792014-10-15 17:38:38 -07001475 mSubMenuVoicemailSettings = (EditPhoneNumberPreference) findPreference(BUTTON_VOICEMAIL_KEY);
1476 mSubMenuVoicemailSettings.setParentActivity(this, VOICEMAIL_PREF_ID, this);
1477 mSubMenuVoicemailSettings.setDialogOnClosedListener(this);
1478 mSubMenuVoicemailSettings.setDialogTitle(R.string.voicemail_settings_number_label);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001479
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001480 mButtonDTMF = (ListPreference) findPreference(BUTTON_DTMF_KEY);
1481 mButtonAutoRetry = (CheckBoxPreference) findPreference(BUTTON_RETRY_KEY);
1482 mButtonHAC = (CheckBoxPreference) findPreference(BUTTON_HAC_KEY);
1483 mButtonTTY = (ListPreference) findPreference(BUTTON_TTY_KEY);
1484 mVoicemailProviders = (ListPreference) findPreference(BUTTON_VOICEMAIL_PROVIDER_KEY);
Andrew Leedf14ead2014-10-17 14:22:52 -07001485 CheckBoxPreference mEnableVideoCalling =
1486 (CheckBoxPreference) findPreference(ENABLE_VIDEO_CALLING_KEY);
Andrew Lee2170a972014-08-13 18:13:01 -07001487
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001488 if (mVoicemailProviders != null) {
1489 mVoicemailProviders.setOnPreferenceChangeListener(this);
Andrew Lee97708a42014-09-25 12:39:07 -07001490 mVoicemailSettingsScreen =
1491 (PreferenceScreen) findPreference(VOICEMAIL_SETTING_SCREEN_PREF_KEY);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001492 mVoicemailSettings = (PreferenceScreen)findPreference(BUTTON_VOICEMAIL_SETTING_KEY);
1493 mVoicemailNotificationRingtone =
1494 findPreference(BUTTON_VOICEMAIL_NOTIFICATION_RINGTONE_KEY);
1495 mVoicemailNotificationVibrate =
1496 (CheckBoxPreference) findPreference(BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY);
1497 initVoiceMailProviders();
1498 }
1499
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001500
Andrew Lee64a7d792014-10-15 17:38:38 -07001501 if (getResources().getBoolean(R.bool.dtmf_type_enabled)) {
1502 mButtonDTMF.setOnPreferenceChangeListener(this);
1503 int dtmf = Settings.System.getInt(getContentResolver(),
1504 Settings.System.DTMF_TONE_TYPE_WHEN_DIALING, Constants.DTMF_TONE_TYPE_NORMAL);
1505 mButtonDTMF.setValueIndex(dtmf);
1506 } else {
1507 prefSet.removePreference(mButtonDTMF);
1508 mButtonDTMF = null;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001509 }
1510
Andrew Lee64a7d792014-10-15 17:38:38 -07001511 if (getResources().getBoolean(R.bool.auto_retry_enabled)) {
1512 mButtonAutoRetry.setOnPreferenceChangeListener(this);
1513 int autoretry = Settings.Global.getInt(
1514 getContentResolver(), Settings.Global.CALL_AUTO_RETRY, 0);
1515 mButtonAutoRetry.setChecked(autoretry != 0);
1516 } else {
1517 prefSet.removePreference(mButtonAutoRetry);
1518 mButtonAutoRetry = null;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001519 }
1520
Andrew Lee64a7d792014-10-15 17:38:38 -07001521 if (getResources().getBoolean(R.bool.hac_enabled)) {
1522 mButtonHAC.setOnPreferenceChangeListener(this);
1523 int hac = Settings.System.getInt(getContentResolver(), Settings.System.HEARING_AID, 0);
1524 mButtonHAC.setChecked(hac != 0);
1525 } else {
1526 prefSet.removePreference(mButtonHAC);
1527 mButtonHAC = null;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001528 }
1529
Andrew Lee64a7d792014-10-15 17:38:38 -07001530 TelecomManager telecomManager = TelecomManager.from(this);
1531 if (telecomManager != null && telecomManager.isTtySupported()) {
1532 mButtonTTY.setOnPreferenceChangeListener(this);
1533 int settingsTtyMode = Settings.Secure.getInt(getContentResolver(),
1534 Settings.Secure.PREFERRED_TTY_MODE,
1535 TelecomManager.TTY_MODE_OFF);
1536 mButtonTTY.setValue(Integer.toString(settingsTtyMode));
1537 updatePreferredTtyModeSummary(settingsTtyMode);
1538 } else {
1539 prefSet.removePreference(mButtonTTY);
1540 mButtonTTY = null;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001541 }
1542
1543 if (!getResources().getBoolean(R.bool.world_phone)) {
1544 Preference options = prefSet.findPreference(BUTTON_CDMA_OPTIONS);
Andrew Lee2170a972014-08-13 18:13:01 -07001545 if (options != null) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001546 prefSet.removePreference(options);
Andrew Lee2170a972014-08-13 18:13:01 -07001547 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001548 options = prefSet.findPreference(BUTTON_GSM_UMTS_OPTIONS);
Andrew Lee2170a972014-08-13 18:13:01 -07001549 if (options != null) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001550 prefSet.removePreference(options);
Andrew Lee2170a972014-08-13 18:13:01 -07001551 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001552
1553 int phoneType = mPhone.getPhoneType();
1554 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1555 Preference fdnButton = prefSet.findPreference(BUTTON_FDN_KEY);
Andrew Lee2170a972014-08-13 18:13:01 -07001556 if (fdnButton != null) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001557 prefSet.removePreference(fdnButton);
Andrew Lee2170a972014-08-13 18:13:01 -07001558 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001559 if (!getResources().getBoolean(R.bool.config_voice_privacy_disable)) {
1560 addPreferencesFromResource(R.xml.cdma_call_privacy);
1561 }
1562 } else if (phoneType == PhoneConstants.PHONE_TYPE_GSM) {
Andrew Lee2170a972014-08-13 18:13:01 -07001563 if (getResources().getBoolean(R.bool.config_additional_call_setting)) {
Etan Cohen0ca1c802014-07-07 15:35:48 -07001564 addPreferencesFromResource(R.xml.gsm_umts_call_options);
1565 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001566 } else {
1567 throw new IllegalStateException("Unexpected phone type: " + phoneType);
1568 }
1569 }
1570
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001571 // check the intent that started this activity and pop up the voicemail
1572 // dialog if we've been asked to.
1573 // If we have at least one non default VM provider registered then bring up
1574 // the selection for the VM provider, otherwise bring up a VM number dialog.
1575 // We only bring up the dialog the first time we are called (not after orientation change)
Tyler Gunnbaee2952014-09-10 16:01:02 -07001576 if (mShowVoicemailPreference && mVoicemailProviders != null) {
1577 if (DBG) {
1578 log("ACTION_ADD_VOICEMAIL Intent is thrown. current VM data size: "
1579 + mVMProvidersData.size());
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001580 }
Tyler Gunnbaee2952014-09-10 16:01:02 -07001581 if (mVMProvidersData.size() > 1) {
1582 simulatePreferenceClick(mVoicemailProviders);
1583 } else {
1584 onPreferenceChange(mVoicemailProviders, DEFAULT_VM_PROVIDER_KEY);
1585 mVoicemailProviders.setValue(DEFAULT_VM_PROVIDER_KEY);
1586 }
1587 mShowVoicemailPreference = false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001588 }
Tyler Gunnbaee2952014-09-10 16:01:02 -07001589
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001590 updateVoiceNumberField();
1591 mVMProviderSettingsForced = false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001592
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001593 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(
1594 mPhone.getContext());
1595 if (migrateVoicemailVibrationSettingsIfNeeded(prefs)) {
1596 mVoicemailNotificationVibrate.setChecked(prefs.getBoolean(
1597 BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY, false));
1598 }
1599
Andrew Lee77527ac2014-10-21 16:57:39 -07001600 if (ImsUtil.isImsEnabled(mPhone.getContext()) && ENABLE_VT_FLAG) {
1601 mEnableVideoCalling.setChecked(
1602 PhoneGlobals.getInstance().phoneMgr.isVideoCallingEnabled());
1603 mEnableVideoCalling.setOnPreferenceChangeListener(this);
1604 } else {
1605 prefSet.removePreference(mEnableVideoCalling);
1606 }
Andrew Leedf14ead2014-10-17 14:22:52 -07001607
Andrew Lee2170a972014-08-13 18:13:01 -07001608 // Look up the voicemail ringtone name asynchronously and update its preference.
1609 new Thread(mVoicemailRingtoneLookupRunnable).start();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001610 }
1611
1612 // Migrate settings from BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_WHEN_KEY to
1613 // BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY, if the latter does not exist.
1614 // Returns true if migration was performed.
1615 public static boolean migrateVoicemailVibrationSettingsIfNeeded(SharedPreferences prefs) {
1616 if (!prefs.contains(BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY)) {
1617 String vibrateWhen = prefs.getString(
1618 BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_WHEN_KEY, VOICEMAIL_VIBRATION_NEVER);
1619 // If vibrateWhen is always, then voicemailVibrate should be True.
1620 // otherwise if vibrateWhen is "only in silent mode", or "never", then
1621 // voicemailVibrate = False.
1622 boolean voicemailVibrate = vibrateWhen.equals(VOICEMAIL_VIBRATION_ALWAYS);
1623 final SharedPreferences.Editor editor = prefs.edit();
1624 editor.putBoolean(BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY, voicemailVibrate);
1625 editor.commit();
1626 return true;
1627 }
1628 return false;
1629 }
1630
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001631 private boolean isAirplaneModeOn() {
1632 return Settings.System.getInt(getContentResolver(),
1633 Settings.System.AIRPLANE_MODE_ON, 0) != 0;
1634 }
1635
1636 private void handleTTYChange(Preference preference, Object objValue) {
1637 int buttonTtyMode;
1638 buttonTtyMode = Integer.valueOf((String) objValue).intValue();
1639 int settingsTtyMode = android.provider.Settings.Secure.getInt(
1640 getContentResolver(),
Sailesh Nepalbf900542014-07-15 16:18:32 -07001641 android.provider.Settings.Secure.PREFERRED_TTY_MODE,
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001642 TelecomManager.TTY_MODE_OFF);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001643 if (DBG) log("handleTTYChange: requesting set TTY mode enable (TTY) to" +
1644 Integer.toString(buttonTtyMode));
1645
1646 if (buttonTtyMode != settingsTtyMode) {
1647 switch(buttonTtyMode) {
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001648 case TelecomManager.TTY_MODE_OFF:
1649 case TelecomManager.TTY_MODE_FULL:
1650 case TelecomManager.TTY_MODE_HCO:
1651 case TelecomManager.TTY_MODE_VCO:
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001652 android.provider.Settings.Secure.putInt(getContentResolver(),
1653 android.provider.Settings.Secure.PREFERRED_TTY_MODE, buttonTtyMode);
1654 break;
1655 default:
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001656 buttonTtyMode = TelecomManager.TTY_MODE_OFF;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001657 }
1658
1659 mButtonTTY.setValue(Integer.toString(buttonTtyMode));
1660 updatePreferredTtyModeSummary(buttonTtyMode);
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001661 Intent ttyModeChanged = new Intent(TelecomManager.ACTION_TTY_PREFERRED_MODE_CHANGED);
1662 ttyModeChanged.putExtra(TelecomManager.EXTRA_TTY_PREFERRED_MODE, buttonTtyMode);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001663 sendBroadcastAsUser(ttyModeChanged, UserHandle.ALL);
1664 }
1665 }
1666
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001667 private void updatePreferredTtyModeSummary(int TtyMode) {
1668 String [] txts = getResources().getStringArray(R.array.tty_mode_entries);
1669 switch(TtyMode) {
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001670 case TelecomManager.TTY_MODE_OFF:
1671 case TelecomManager.TTY_MODE_HCO:
1672 case TelecomManager.TTY_MODE_VCO:
1673 case TelecomManager.TTY_MODE_FULL:
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001674 mButtonTTY.setSummary(txts[TtyMode]);
1675 break;
1676 default:
1677 mButtonTTY.setEnabled(false);
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001678 mButtonTTY.setSummary(txts[TelecomManager.TTY_MODE_OFF]);
Sailesh Nepalbf900542014-07-15 16:18:32 -07001679 break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001680 }
1681 }
1682
1683 private static void log(String msg) {
1684 Log.d(LOG_TAG, msg);
1685 }
1686
1687 /**
1688 * Updates the look of the VM preference widgets based on current VM provider settings.
1689 * Note that the provider name is loaded form the found activity via loadLabel in
1690 * {@link #initVoiceMailProviders()} in order for it to be localizable.
1691 */
1692 private void updateVMPreferenceWidgets(String currentProviderSetting) {
1693 final String key = currentProviderSetting;
1694 final VoiceMailProvider provider = mVMProvidersData.get(key);
1695
1696 /* This is the case when we are coming up on a freshly wiped phone and there is no
1697 persisted value for the list preference mVoicemailProviders.
1698 In this case we want to show the UI asking the user to select a voicemail provider as
1699 opposed to silently falling back to default one. */
1700 if (provider == null) {
1701 if (DBG) {
1702 log("updateVMPreferenceWidget: provider for the key \"" + key + "\" is null.");
1703 }
1704 mVoicemailProviders.setSummary(getString(R.string.sum_voicemail_choose_provider));
1705 mVoicemailSettings.setEnabled(false);
1706 mVoicemailSettings.setIntent(null);
1707
1708 mVoicemailNotificationVibrate.setEnabled(false);
1709 } else {
1710 if (DBG) {
1711 log("updateVMPreferenceWidget: provider for the key \"" + key + "\".."
1712 + "name: " + provider.name
1713 + ", intent: " + provider.intent);
1714 }
1715 final String providerName = provider.name;
1716 mVoicemailProviders.setSummary(providerName);
1717 mVoicemailSettings.setEnabled(true);
1718 mVoicemailSettings.setIntent(provider.intent);
1719
1720 mVoicemailNotificationVibrate.setEnabled(true);
1721 }
1722 }
1723
1724 /**
1725 * Enumerates existing VM providers and puts their data into the list and populates
1726 * the preference list objects with their names.
1727 * In case we are called with ACTION_ADD_VOICEMAIL intent the intent may have
1728 * an extra string called IGNORE_PROVIDER_EXTRA with "package.activityName" of the provider
1729 * which should be hidden when we bring up the list of possible VM providers to choose.
1730 */
1731 private void initVoiceMailProviders() {
1732 if (DBG) log("initVoiceMailProviders()");
1733 mPerProviderSavedVMNumbers =
1734 this.getApplicationContext().getSharedPreferences(
1735 VM_NUMBERS_SHARED_PREFERENCES_NAME, MODE_PRIVATE);
1736
1737 String providerToIgnore = null;
1738 if (getIntent().getAction().equals(ACTION_ADD_VOICEMAIL)) {
1739 if (getIntent().hasExtra(IGNORE_PROVIDER_EXTRA)) {
1740 providerToIgnore = getIntent().getStringExtra(IGNORE_PROVIDER_EXTRA);
1741 }
1742 if (DBG) log("Found ACTION_ADD_VOICEMAIL. providerToIgnore=" + providerToIgnore);
1743 if (providerToIgnore != null) {
1744 // IGNORE_PROVIDER_EXTRA implies we want to remove the choice from the list.
1745 deleteSettingsForVoicemailProvider(providerToIgnore);
1746 }
1747 }
1748
1749 mVMProvidersData.clear();
1750
1751 // Stick the default element which is always there
1752 final String myCarrier = getString(R.string.voicemail_default);
1753 mVMProvidersData.put(DEFAULT_VM_PROVIDER_KEY, new VoiceMailProvider(myCarrier, null));
1754
1755 // Enumerate providers
1756 PackageManager pm = getPackageManager();
1757 Intent intent = new Intent();
1758 intent.setAction(ACTION_CONFIGURE_VOICEMAIL);
1759 List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
1760 int len = resolveInfos.size() + 1; // +1 for the default choice we will insert.
1761
1762 // Go through the list of discovered providers populating the data map
1763 // skip the provider we were instructed to ignore if there was one
1764 for (int i = 0; i < resolveInfos.size(); i++) {
1765 final ResolveInfo ri= resolveInfos.get(i);
1766 final ActivityInfo currentActivityInfo = ri.activityInfo;
1767 final String key = makeKeyForActivity(currentActivityInfo);
1768 if (key.equals(providerToIgnore)) {
1769 if (DBG) log("Ignoring key: " + key);
1770 len--;
1771 continue;
1772 }
1773 if (DBG) log("Loading key: " + key);
1774 final String nameForDisplay = ri.loadLabel(pm).toString();
1775 Intent providerIntent = new Intent();
1776 providerIntent.setAction(ACTION_CONFIGURE_VOICEMAIL);
1777 providerIntent.setClassName(currentActivityInfo.packageName,
1778 currentActivityInfo.name);
1779 if (DBG) {
1780 log("Store loaded VoiceMailProvider. key: " + key
1781 + " -> name: " + nameForDisplay + ", intent: " + providerIntent);
1782 }
1783 mVMProvidersData.put(
1784 key,
1785 new VoiceMailProvider(nameForDisplay, providerIntent));
1786
1787 }
1788
1789 // Now we know which providers to display - create entries and values array for
1790 // the list preference
1791 String [] entries = new String [len];
1792 String [] values = new String [len];
1793 entries[0] = myCarrier;
1794 values[0] = DEFAULT_VM_PROVIDER_KEY;
1795 int entryIdx = 1;
1796 for (int i = 0; i < resolveInfos.size(); i++) {
1797 final String key = makeKeyForActivity(resolveInfos.get(i).activityInfo);
1798 if (!mVMProvidersData.containsKey(key)) {
1799 continue;
1800 }
1801 entries[entryIdx] = mVMProvidersData.get(key).name;
1802 values[entryIdx] = key;
1803 entryIdx++;
1804 }
1805
1806 // ListPreference is now updated.
1807 mVoicemailProviders.setEntries(entries);
1808 mVoicemailProviders.setEntryValues(values);
1809
1810 // Remember the current Voicemail Provider key as a "previous" key. This will be used
1811 // when we fail to update Voicemail Provider, which requires rollback.
1812 // We will update this when the VM Provider setting is successfully updated.
1813 mPreviousVMProviderKey = getCurrentVoicemailProviderKey();
1814 if (DBG) log("Set up the first mPreviousVMProviderKey: " + mPreviousVMProviderKey);
1815
1816 // Finally update the preference texts.
1817 updateVMPreferenceWidgets(mPreviousVMProviderKey);
1818 }
1819
1820 private String makeKeyForActivity(ActivityInfo ai) {
1821 return ai.name;
1822 }
1823
1824 /**
1825 * Simulates user clicking on a passed preference.
1826 * Usually needed when the preference is a dialog preference and we want to invoke
1827 * a dialog for this preference programmatically.
Santos Cordonda120f42014-08-06 04:44:34 -07001828 * TODO: figure out if there is a cleaner way to cause preference dlg to come up
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001829 */
1830 private void simulatePreferenceClick(Preference preference) {
1831 // Go through settings until we find our setting
1832 // and then simulate a click on it to bring up the dialog
1833 final ListAdapter adapter = getPreferenceScreen().getRootAdapter();
1834 for (int idx = 0; idx < adapter.getCount(); idx++) {
1835 if (adapter.getItem(idx) == preference) {
1836 getPreferenceScreen().onItemClick(this.getListView(),
1837 null, idx, adapter.getItemId(idx));
1838 break;
1839 }
1840 }
1841 }
1842
1843 /**
1844 * Saves new VM provider settings associating them with the currently selected
1845 * provider if settings are different than the ones already stored for this
1846 * provider.
1847 * Later on these will be used when the user switches a provider.
1848 */
1849 private void maybeSaveSettingsForVoicemailProvider(String key,
Andrew Leeb490d732014-10-27 15:00:41 -07001850 VoicemailProviderSettings newSettings) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001851 if (mVoicemailProviders == null) {
1852 return;
1853 }
Andrew Leeb490d732014-10-27 15:00:41 -07001854 final VoicemailProviderSettings curSettings = loadSettingsForVoiceMailProvider(key);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001855 if (newSettings.equals(curSettings)) {
1856 if (DBG) {
1857 log("maybeSaveSettingsForVoicemailProvider:"
1858 + " Not saving setting for " + key + " since they have not changed");
1859 }
1860 return;
1861 }
1862 if (DBG) log("Saving settings for " + key + ": " + newSettings.toString());
1863 Editor editor = mPerProviderSavedVMNumbers.edit();
Andrew Leeb490d732014-10-27 15:00:41 -07001864 editor.putString(key + VM_NUMBER_TAG, newSettings.getVoicemailNumber());
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001865 String fwdKey = key + FWD_SETTINGS_TAG;
Andrew Leeb490d732014-10-27 15:00:41 -07001866 CallForwardInfo[] s = newSettings.getForwardingSettings();
1867 if (s != VoicemailProviderSettings.NO_FORWARDING) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001868 editor.putInt(fwdKey + FWD_SETTINGS_LENGTH_TAG, s.length);
1869 for (int i = 0; i < s.length; i++) {
1870 final String settingKey = fwdKey + FWD_SETTING_TAG + String.valueOf(i);
1871 final CallForwardInfo fi = s[i];
1872 editor.putInt(settingKey + FWD_SETTING_STATUS, fi.status);
1873 editor.putInt(settingKey + FWD_SETTING_REASON, fi.reason);
1874 editor.putString(settingKey + FWD_SETTING_NUMBER, fi.number);
1875 editor.putInt(settingKey + FWD_SETTING_TIME, fi.timeSeconds);
1876 }
1877 } else {
1878 editor.putInt(fwdKey + FWD_SETTINGS_LENGTH_TAG, 0);
1879 }
1880 editor.apply();
1881 }
1882
1883 /**
1884 * Returns settings previously stored for the currently selected
1885 * voice mail provider. If none is stored returns null.
1886 * If the user switches to a voice mail provider and we have settings
1887 * stored for it we will automatically change the phone's voice mail number
1888 * and forwarding number to the stored one. Otherwise we will bring up provider's configuration
1889 * UI.
1890 */
Andrew Leeb490d732014-10-27 15:00:41 -07001891 private VoicemailProviderSettings loadSettingsForVoiceMailProvider(String key) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001892 final String vmNumberSetting = mPerProviderSavedVMNumbers.getString(key + VM_NUMBER_TAG,
1893 null);
1894 if (vmNumberSetting == null) {
1895 Log.w(LOG_TAG, "VoiceMailProvider settings for the key \"" + key + "\""
1896 + " was not found. Returning null.");
1897 return null;
1898 }
1899
Andrew Leeb490d732014-10-27 15:00:41 -07001900 CallForwardInfo[] cfi = VoicemailProviderSettings.NO_FORWARDING;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001901 String fwdKey = key + FWD_SETTINGS_TAG;
1902 final int fwdLen = mPerProviderSavedVMNumbers.getInt(fwdKey + FWD_SETTINGS_LENGTH_TAG, 0);
1903 if (fwdLen > 0) {
1904 cfi = new CallForwardInfo[fwdLen];
1905 for (int i = 0; i < cfi.length; i++) {
1906 final String settingKey = fwdKey + FWD_SETTING_TAG + String.valueOf(i);
1907 cfi[i] = new CallForwardInfo();
1908 cfi[i].status = mPerProviderSavedVMNumbers.getInt(
1909 settingKey + FWD_SETTING_STATUS, 0);
1910 cfi[i].reason = mPerProviderSavedVMNumbers.getInt(
1911 settingKey + FWD_SETTING_REASON,
1912 CommandsInterface.CF_REASON_ALL_CONDITIONAL);
1913 cfi[i].serviceClass = CommandsInterface.SERVICE_CLASS_VOICE;
1914 cfi[i].toa = PhoneNumberUtils.TOA_International;
1915 cfi[i].number = mPerProviderSavedVMNumbers.getString(
1916 settingKey + FWD_SETTING_NUMBER, "");
1917 cfi[i].timeSeconds = mPerProviderSavedVMNumbers.getInt(
1918 settingKey + FWD_SETTING_TIME, 20);
1919 }
1920 }
1921
Andrew Leeb490d732014-10-27 15:00:41 -07001922 VoicemailProviderSettings settings = new VoicemailProviderSettings(vmNumberSetting, cfi);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001923 if (DBG) log("Loaded settings for " + key + ": " + settings.toString());
1924 return settings;
1925 }
1926
1927 /**
1928 * Deletes settings for the specified provider.
1929 */
1930 private void deleteSettingsForVoicemailProvider(String key) {
1931 if (DBG) log("Deleting settings for" + key);
1932 if (mVoicemailProviders == null) {
1933 return;
1934 }
1935 mPerProviderSavedVMNumbers.edit()
1936 .putString(key + VM_NUMBER_TAG, null)
1937 .putInt(key + FWD_SETTINGS_TAG + FWD_SETTINGS_LENGTH_TAG, 0)
1938 .commit();
1939 }
1940
1941 private String getCurrentVoicemailProviderKey() {
1942 final String key = mVoicemailProviders.getValue();
1943 return (key != null) ? key : DEFAULT_VM_PROVIDER_KEY;
1944 }
1945
1946 @Override
1947 public boolean onOptionsItemSelected(MenuItem item) {
1948 final int itemId = item.getItemId();
1949 if (itemId == android.R.id.home) { // See ActionBar#setDisplayHomeAsUpEnabled()
Yorke Leef2d0cac2013-09-09 19:42:56 -07001950 onBackPressed();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001951 return true;
1952 }
1953 return super.onOptionsItemSelected(item);
1954 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001955 /**
1956 * Finish current Activity and go up to the top level Settings ({@link CallFeaturesSetting}).
1957 * This is useful for implementing "HomeAsUp" capability for second-level Settings.
1958 */
1959 public static void goUpToTopLevelSetting(Activity activity) {
1960 Intent intent = new Intent(activity, CallFeaturesSetting.class);
1961 intent.setAction(Intent.ACTION_MAIN);
1962 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
1963 activity.startActivity(intent);
1964 activity.finish();
1965 }
1966}