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