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