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