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