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