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