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