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