blob: 7c828f93646fbf3541a6fafcd6ea6d9effe94c34 [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);
Andrew Lee77527ac2014-10-21 16:57:39 -0700101 // STOPSHIP if true. Flag to override behavior default behavior to hide VT setting.
102 private static final boolean ENABLE_VT_FLAG = false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700103
104 /**
105 * Intent action to bring up Voicemail Provider settings.
106 *
107 * @see #IGNORE_PROVIDER_EXTRA
108 */
109 public static final String ACTION_ADD_VOICEMAIL =
110 "com.android.phone.CallFeaturesSetting.ADD_VOICEMAIL";
111 // intent action sent by this activity to a voice mail provider
112 // to trigger its configuration UI
113 public static final String ACTION_CONFIGURE_VOICEMAIL =
114 "com.android.phone.CallFeaturesSetting.CONFIGURE_VOICEMAIL";
115 // Extra put in the return from VM provider config containing voicemail number to set
116 public static final String VM_NUMBER_EXTRA = "com.android.phone.VoicemailNumber";
117 // Extra put in the return from VM provider config containing call forwarding number to set
118 public static final String FWD_NUMBER_EXTRA = "com.android.phone.ForwardingNumber";
119 // Extra put in the return from VM provider config containing call forwarding number to set
120 public static final String FWD_NUMBER_TIME_EXTRA = "com.android.phone.ForwardingNumberTime";
121 // If the VM provider returns non null value in this extra we will force the user to
122 // choose another VM provider
123 public static final String SIGNOUT_EXTRA = "com.android.phone.Signout";
124 //Information about logical "up" Activity
125 private static final String UP_ACTIVITY_PACKAGE = "com.android.dialer";
126 private static final String UP_ACTIVITY_CLASS =
127 "com.android.dialer.DialtactsActivity";
128
129 // Used to tell the saving logic to leave forwarding number as is
130 public static final CallForwardInfo[] FWD_SETTINGS_DONT_TOUCH = null;
131 // Suffix appended to provider key for storing vm number
132 public static final String VM_NUMBER_TAG = "#VMNumber";
133 // Suffix appended to provider key for storing forwarding settings
134 public static final String FWD_SETTINGS_TAG = "#FWDSettings";
135 // Suffix appended to forward settings key for storing length of settings array
136 public static final String FWD_SETTINGS_LENGTH_TAG = "#Length";
137 // Suffix appended to forward settings key for storing an individual setting
138 public static final String FWD_SETTING_TAG = "#Setting";
139 // Suffixes appended to forward setting key for storing an individual setting properties
140 public static final String FWD_SETTING_STATUS = "#Status";
141 public static final String FWD_SETTING_REASON = "#Reason";
142 public static final String FWD_SETTING_NUMBER = "#Number";
143 public static final String FWD_SETTING_TIME = "#Time";
144
145 // Key identifying the default vocie mail provider
146 public static final String DEFAULT_VM_PROVIDER_KEY = "";
147
148 /**
149 * String Extra put into ACTION_ADD_VOICEMAIL call to indicate which provider should be hidden
150 * in the list of providers presented to the user. This allows a provider which is being
151 * disabled (e.g. GV user logging out) to force the user to pick some other provider.
152 */
153 public static final String IGNORE_PROVIDER_EXTRA = "com.android.phone.ProviderToIgnore";
154
155 // string constants
156 private static final String NUM_PROJECTION[] = {CommonDataKinds.Phone.NUMBER};
157
158 // String keys for preference lookup
159 // TODO: Naming these "BUTTON_*" is confusing since they're not actually buttons(!)
Andrew Lee97708a42014-09-25 12:39:07 -0700160 private static final String VOICEMAIL_SETTING_SCREEN_PREF_KEY = "button_voicemail_category_key";
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700161 private static final String BUTTON_VOICEMAIL_KEY = "button_voicemail_key";
162 private static final String BUTTON_VOICEMAIL_PROVIDER_KEY = "button_voicemail_provider_key";
163 private static final String BUTTON_VOICEMAIL_SETTING_KEY = "button_voicemail_setting_key";
164 // New preference key for voicemail notification vibration
165 /* package */ static final String BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY =
166 "button_voicemail_notification_vibrate_key";
167 // Old preference key for voicemail notification vibration. Used for migration to the new
168 // preference key only.
169 /* package */ static final String BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_WHEN_KEY =
170 "button_voicemail_notification_vibrate_when_key";
171 /* package */ static final String BUTTON_VOICEMAIL_NOTIFICATION_RINGTONE_KEY =
172 "button_voicemail_notification_ringtone_key";
173 private static final String BUTTON_FDN_KEY = "button_fdn_key";
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700174
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700175 private static final String BUTTON_DTMF_KEY = "button_dtmf_settings";
176 private static final String BUTTON_RETRY_KEY = "button_auto_retry_key";
177 private static final String BUTTON_TTY_KEY = "button_tty_mode_key";
178 private static final String BUTTON_HAC_KEY = "button_hac_key";
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700179
180 private static final String BUTTON_GSM_UMTS_OPTIONS = "button_gsm_more_expand_key";
181 private static final String BUTTON_CDMA_OPTIONS = "button_cdma_more_expand_key";
182
183 private static final String VM_NUMBERS_SHARED_PREFERENCES_NAME = "vm_numbers";
184
Andrew Leedb2fe562014-09-03 15:40:43 -0700185 private static final String DEFAULT_OUTGOING_ACCOUNT_KEY = "default_outgoing_account";
Andrew Leece8ae2a2014-09-10 10:41:48 -0700186 private static final String PHONE_ACCOUNT_SETTINGS_KEY =
187 "phone_account_settings_preference_screen";
Andrew Leedb2fe562014-09-03 15:40:43 -0700188
Andrew Leedf14ead2014-10-17 14:22:52 -0700189 private static final String ENABLE_VIDEO_CALLING_KEY = "button_enable_video_calling";
190
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700191 private Intent mContactListIntent;
192
193 /** Event for Async voicemail change call */
194 private static final int EVENT_VOICEMAIL_CHANGED = 500;
195 private static final int EVENT_FORWARDING_CHANGED = 501;
196 private static final int EVENT_FORWARDING_GET_COMPLETED = 502;
197
Andrew Lee2170a972014-08-13 18:13:01 -0700198 private static final int MSG_UPDATE_VOICEMAIL_RINGTONE_SUMMARY = 1;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700199
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700200 public static final String HAC_KEY = "HACSetting";
201 public static final String HAC_VAL_ON = "ON";
202 public static final String HAC_VAL_OFF = "OFF";
203
204 /** Handle to voicemail pref */
205 private static final int VOICEMAIL_PREF_ID = 1;
206 private static final int VOICEMAIL_PROVIDER_CFG_ID = 2;
207
208 private Phone mPhone;
209
210 private AudioManager mAudioManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700211
212 private static final int VM_NOCHANGE_ERROR = 400;
213 private static final int VM_RESPONSE_ERROR = 500;
214 private static final int FW_SET_RESPONSE_ERROR = 501;
215 private static final int FW_GET_RESPONSE_ERROR = 502;
216
217
218 // dialog identifiers for voicemail
219 private static final int VOICEMAIL_DIALOG_CONFIRM = 600;
220 private static final int VOICEMAIL_FWD_SAVING_DIALOG = 601;
221 private static final int VOICEMAIL_FWD_READING_DIALOG = 602;
222 private static final int VOICEMAIL_REVERTING_DIALOG = 603;
223
224 // status message sent back from handlers
225 private static final int MSG_OK = 100;
226
227 // special statuses for voicemail controls.
228 private static final int MSG_VM_EXCEPTION = 400;
229 private static final int MSG_FW_SET_EXCEPTION = 401;
230 private static final int MSG_FW_GET_EXCEPTION = 402;
231 private static final int MSG_VM_OK = 600;
232 private static final int MSG_VM_NOCHANGE = 700;
233
234 // voicemail notification vibration string constants
235 private static final String VOICEMAIL_VIBRATION_ALWAYS = "always";
236 private static final String VOICEMAIL_VIBRATION_NEVER = "never";
237
238 private EditPhoneNumberPreference mSubMenuVoicemailSettings;
239
Andrew Lee2170a972014-08-13 18:13:01 -0700240 private Runnable mVoicemailRingtoneLookupRunnable;
241 private final Handler mVoicemailRingtoneLookupComplete = new Handler() {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700242 @Override
243 public void handleMessage(Message msg) {
244 switch (msg.what) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700245 case MSG_UPDATE_VOICEMAIL_RINGTONE_SUMMARY:
246 mVoicemailNotificationRingtone.setSummary((CharSequence) msg.obj);
247 break;
248 }
249 }
250 };
251
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700252 /** Whether dialpad plays DTMF tone or not. */
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700253 private CheckBoxPreference mButtonAutoRetry;
254 private CheckBoxPreference mButtonHAC;
255 private ListPreference mButtonDTMF;
256 private ListPreference mButtonTTY;
Andrew Leece8ae2a2014-09-10 10:41:48 -0700257 private Preference mPhoneAccountSettingsPreference;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700258 private ListPreference mVoicemailProviders;
Andrew Lee97708a42014-09-25 12:39:07 -0700259 private PreferenceScreen mVoicemailSettingsScreen;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700260 private PreferenceScreen mVoicemailSettings;
261 private Preference mVoicemailNotificationRingtone;
262 private CheckBoxPreference mVoicemailNotificationVibrate;
Andrew Leedb2fe562014-09-03 15:40:43 -0700263 private AccountSelectionPreference mDefaultOutgoingAccount;
Andrew Leedf14ead2014-10-17 14:22:52 -0700264 private CheckBoxPreference mEnableVideoCalling;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700265
266 private class VoiceMailProvider {
267 public VoiceMailProvider(String name, Intent intent) {
268 this.name = name;
269 this.intent = intent;
270 }
271 public String name;
272 public Intent intent;
273 }
274
275 /**
276 * Forwarding settings we are going to save.
277 */
278 private static final int [] FORWARDING_SETTINGS_REASONS = new int[] {
279 CommandsInterface.CF_REASON_UNCONDITIONAL,
280 CommandsInterface.CF_REASON_BUSY,
281 CommandsInterface.CF_REASON_NO_REPLY,
282 CommandsInterface.CF_REASON_NOT_REACHABLE
283 };
284
285 private class VoiceMailProviderSettings {
286 /**
287 * Constructs settings object, setting all conditional forwarding to the specified number
288 */
289 public VoiceMailProviderSettings(String voicemailNumber, String forwardingNumber,
290 int timeSeconds) {
291 this.voicemailNumber = voicemailNumber;
292 if (forwardingNumber == null || forwardingNumber.length() == 0) {
293 this.forwardingSettings = FWD_SETTINGS_DONT_TOUCH;
294 } else {
295 this.forwardingSettings = new CallForwardInfo[FORWARDING_SETTINGS_REASONS.length];
296 for (int i = 0; i < this.forwardingSettings.length; i++) {
297 CallForwardInfo fi = new CallForwardInfo();
298 this.forwardingSettings[i] = fi;
299 fi.reason = FORWARDING_SETTINGS_REASONS[i];
300 fi.status = (fi.reason == CommandsInterface.CF_REASON_UNCONDITIONAL) ? 0 : 1;
301 fi.serviceClass = CommandsInterface.SERVICE_CLASS_VOICE;
302 fi.toa = PhoneNumberUtils.TOA_International;
303 fi.number = forwardingNumber;
304 fi.timeSeconds = timeSeconds;
305 }
306 }
307 }
308
309 public VoiceMailProviderSettings(String voicemailNumber, CallForwardInfo[] infos) {
310 this.voicemailNumber = voicemailNumber;
311 this.forwardingSettings = infos;
312 }
313
314 @Override
315 public boolean equals(Object o) {
316 if (o == null) return false;
317 if (!(o instanceof VoiceMailProviderSettings)) return false;
318 final VoiceMailProviderSettings v = (VoiceMailProviderSettings)o;
319
320 return ((this.voicemailNumber == null &&
321 v.voicemailNumber == null) ||
322 this.voicemailNumber != null &&
323 this.voicemailNumber.equals(v.voicemailNumber))
324 &&
325 forwardingSettingsEqual(this.forwardingSettings,
326 v.forwardingSettings);
327 }
328
329 private boolean forwardingSettingsEqual(CallForwardInfo[] infos1,
330 CallForwardInfo[] infos2) {
331 if (infos1 == infos2) return true;
332 if (infos1 == null || infos2 == null) return false;
333 if (infos1.length != infos2.length) return false;
334 for (int i = 0; i < infos1.length; i++) {
335 CallForwardInfo i1 = infos1[i];
336 CallForwardInfo i2 = infos2[i];
337 if (i1.status != i2.status ||
338 i1.reason != i2.reason ||
339 i1.serviceClass != i2.serviceClass ||
340 i1.toa != i2.toa ||
341 i1.number != i2.number ||
342 i1.timeSeconds != i2.timeSeconds) {
343 return false;
344 }
345 }
346 return true;
347 }
348
349 @Override
350 public String toString() {
351 return voicemailNumber + ((forwardingSettings != null ) ? (", " +
352 forwardingSettings.toString()) : "");
353 }
354
355 public String voicemailNumber;
356 public CallForwardInfo[] forwardingSettings;
357 }
358
359 private SharedPreferences mPerProviderSavedVMNumbers;
360
361 /**
362 * Results of reading forwarding settings
363 */
364 private CallForwardInfo[] mForwardingReadResults = null;
365
366 /**
367 * Result of forwarding number change.
368 * Keys are reasons (eg. unconditional forwarding).
369 */
370 private Map<Integer, AsyncResult> mForwardingChangeResults = null;
371
372 /**
373 * Expected CF read result types.
374 * This set keeps track of the CF types for which we've issued change
375 * commands so we can tell when we've received all of the responses.
376 */
377 private Collection<Integer> mExpectedChangeResultReasons = null;
378
379 /**
380 * Result of vm number change
381 */
382 private AsyncResult mVoicemailChangeResult = null;
383
384 /**
385 * Previous VM provider setting so we can return to it in case of failure.
386 */
387 private String mPreviousVMProviderKey = null;
388
389 /**
390 * Id of the dialog being currently shown.
391 */
392 private int mCurrentDialogId = 0;
393
394 /**
395 * Flag indicating that we are invoking settings for the voicemail provider programmatically
396 * due to vm provider change.
397 */
398 private boolean mVMProviderSettingsForced = false;
399
400 /**
401 * Flag indicating that we are making changes to vm or fwd numbers
402 * due to vm provider change.
403 */
404 private boolean mChangingVMorFwdDueToProviderChange = false;
405
406 /**
407 * True if we are in the process of vm & fwd number change and vm has already been changed.
408 * This is used to decide what to do in case of rollback.
409 */
410 private boolean mVMChangeCompletedSuccessfully = false;
411
412 /**
413 * True if we had full or partial failure setting forwarding numbers and so need to roll them
414 * back.
415 */
416 private boolean mFwdChangesRequireRollback = false;
417
418 /**
419 * Id of error msg to display to user once we are done reverting the VM provider to the previous
420 * one.
421 */
422 private int mVMOrFwdSetError = 0;
423
424 /**
425 * Data about discovered voice mail settings providers.
426 * Is populated by querying which activities can handle ACTION_CONFIGURE_VOICEMAIL.
427 * They key in this map is package name + activity name.
428 * We always add an entry for the default provider with a key of empty
429 * string and intent value of null.
430 * @see #initVoiceMailProviders()
431 */
432 private final Map<String, VoiceMailProvider> mVMProvidersData =
433 new HashMap<String, VoiceMailProvider>();
434
435 /** string to hold old voicemail number as it is being updated. */
436 private String mOldVmNumber;
437
438 // New call forwarding settings and vm number we will be setting
439 // Need to save these since before we get to saving we need to asynchronously
440 // query the existing forwarding settings.
441 private CallForwardInfo[] mNewFwdSettings;
442 private String mNewVMNumber;
443
444 private boolean mForeground;
445
446 @Override
447 public void onPause() {
448 super.onPause();
449 mForeground = false;
450 }
451
452 /**
453 * We have to pull current settings from the network for all kinds of
454 * voicemail providers so we can tell whether we have to update them,
455 * so use this bit to keep track of whether we're reading settings for the
456 * default provider and should therefore save them out when done.
457 */
458 private boolean mReadingSettingsForDefaultProvider = false;
459
Tyler Gunnbaee2952014-09-10 16:01:02 -0700460 /**
461 * Used to indicate that the voicemail preference should be shown.
462 */
463 private boolean mShowVoicemailPreference = false;
464
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700465 /*
466 * Click Listeners, handle click based on objects attached to UI.
467 */
468
469 // Click listener for all toggle events
470 @Override
471 public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
472 if (preference == mSubMenuVoicemailSettings) {
473 return true;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700474 } else if (preference == mButtonDTMF) {
475 return true;
476 } else if (preference == mButtonTTY) {
477 return true;
478 } else if (preference == mButtonAutoRetry) {
479 android.provider.Settings.Global.putInt(mPhone.getContext().getContentResolver(),
480 android.provider.Settings.Global.CALL_AUTO_RETRY,
481 mButtonAutoRetry.isChecked() ? 1 : 0);
482 return true;
483 } else if (preference == mButtonHAC) {
484 int hac = mButtonHAC.isChecked() ? 1 : 0;
485 // Update HAC value in Settings database
486 Settings.System.putInt(mPhone.getContext().getContentResolver(),
487 Settings.System.HEARING_AID, hac);
488
489 // Update HAC Value in AudioManager
490 mAudioManager.setParameter(HAC_KEY, hac != 0 ? HAC_VAL_ON : HAC_VAL_OFF);
491 return true;
492 } else if (preference == mVoicemailSettings) {
Yorke Leea0f63bf2014-10-09 18:27:20 -0700493 final Dialog dialog = mVoicemailSettings.getDialog();
494 if (dialog != null) {
495 dialog.getActionBar().setDisplayHomeAsUpEnabled(false);
496 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700497 if (DBG) log("onPreferenceTreeClick: Voicemail Settings Preference is clicked.");
498 if (preference.getIntent() != null) {
499 if (DBG) {
500 log("onPreferenceTreeClick: Invoking cfg intent "
501 + preference.getIntent().getPackage());
502 }
503
504 // onActivityResult() will be responsible for resetting some of variables.
505 this.startActivityForResult(preference.getIntent(), VOICEMAIL_PROVIDER_CFG_ID);
506 return true;
507 } else {
508 if (DBG) {
509 log("onPreferenceTreeClick:"
510 + " No Intent is available. Use default behavior defined in xml.");
511 }
512
513 // There's no onActivityResult(), so we need to take care of some of variables
514 // which should be reset here.
515 mPreviousVMProviderKey = DEFAULT_VM_PROVIDER_KEY;
516 mVMProviderSettingsForced = false;
517
518 // This should let the preference use default behavior in the xml.
519 return false;
520 }
Andrew Lee97708a42014-09-25 12:39:07 -0700521 } else if (preference == mVoicemailSettingsScreen) {
Yorke Leea0f63bf2014-10-09 18:27:20 -0700522 final Dialog dialog = mVoicemailSettingsScreen.getDialog();
523 if (dialog != null) {
524 dialog.getActionBar().setDisplayHomeAsUpEnabled(false);
525 }
Andrew Lee97708a42014-09-25 12:39:07 -0700526 return false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700527 }
528 return false;
529 }
530
531 /**
532 * Implemented to support onPreferenceChangeListener to look for preference
533 * changes.
534 *
535 * @param preference is the preference to be changed
536 * @param objValue should be the value of the selection, NOT its localized
537 * display value.
538 */
539 @Override
540 public boolean onPreferenceChange(Preference preference, Object objValue) {
541 if (DBG) {
Andrew Leedf14ead2014-10-17 14:22:52 -0700542 log("onPreferenceChange(). preference: \"" + preference + "\""
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700543 + ", value: \"" + objValue + "\"");
544 }
Andrew Lee2170a972014-08-13 18:13:01 -0700545
546 if (preference == mButtonDTMF) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700547 int index = mButtonDTMF.findIndexOfValue((String) objValue);
548 Settings.System.putInt(mPhone.getContext().getContentResolver(),
549 Settings.System.DTMF_TONE_TYPE_WHEN_DIALING, index);
550 } else if (preference == mButtonTTY) {
551 handleTTYChange(preference, objValue);
552 } else if (preference == mVoicemailProviders) {
553 final String newProviderKey = (String) objValue;
554 if (DBG) {
555 log("Voicemail Provider changes from \"" + mPreviousVMProviderKey
556 + "\" to \"" + newProviderKey + "\".");
557 }
558 // If previous provider key and the new one is same, we don't need to handle it.
559 if (mPreviousVMProviderKey.equals(newProviderKey)) {
560 if (DBG) log("No change is made toward VM provider setting.");
561 return true;
562 }
563 updateVMPreferenceWidgets(newProviderKey);
564
565 final VoiceMailProviderSettings newProviderSettings =
566 loadSettingsForVoiceMailProvider(newProviderKey);
567
568 // If the user switches to a voice mail provider and we have a
569 // numbers stored for it we will automatically change the
570 // phone's
571 // voice mail and forwarding number to the stored ones.
572 // Otherwise we will bring up provider's configuration UI.
573
574 if (newProviderSettings == null) {
575 // Force the user into a configuration of the chosen provider
576 Log.w(LOG_TAG, "Saved preferences not found - invoking config");
577 mVMProviderSettingsForced = true;
578 simulatePreferenceClick(mVoicemailSettings);
579 } else {
580 if (DBG) log("Saved preferences found - switching to them");
581 // Set this flag so if we get a failure we revert to previous provider
582 mChangingVMorFwdDueToProviderChange = true;
583 saveVoiceMailAndForwardingNumber(newProviderKey, newProviderSettings);
584 }
Andrew Leedf14ead2014-10-17 14:22:52 -0700585 } else if (preference == mEnableVideoCalling) {
586 PhoneGlobals.getInstance().phoneMgr.enableVideoCalling((boolean) objValue);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700587 }
588 // always let the preference setting proceed.
589 return true;
590 }
591
592 @Override
593 public void onDialogClosed(EditPhoneNumberPreference preference, int buttonClicked) {
594 if (DBG) log("onPreferenceClick: request preference click on dialog close: " +
595 buttonClicked);
596 if (buttonClicked == DialogInterface.BUTTON_NEGATIVE) {
597 return;
598 }
599
600 if (preference == mSubMenuVoicemailSettings) {
601 handleVMBtnClickRequest();
602 }
603 }
604
605 /**
606 * Implemented for EditPhoneNumberPreference.GetDefaultNumberListener.
607 * This method set the default values for the various
608 * EditPhoneNumberPreference dialogs.
609 */
610 @Override
611 public String onGetDefaultNumber(EditPhoneNumberPreference preference) {
612 if (preference == mSubMenuVoicemailSettings) {
613 // update the voicemail number field, which takes care of the
614 // mSubMenuVoicemailSettings itself, so we should return null.
615 if (DBG) log("updating default for voicemail dialog");
616 updateVoiceNumberField();
617 return null;
618 }
619
620 String vmDisplay = mPhone.getVoiceMailNumber();
621 if (TextUtils.isEmpty(vmDisplay)) {
622 // if there is no voicemail number, we just return null to
623 // indicate no contribution.
624 return null;
625 }
626
627 // Return the voicemail number prepended with "VM: "
628 if (DBG) log("updating default for call forwarding dialogs");
629 return getString(R.string.voicemail_abbreviated) + " " + vmDisplay;
630 }
631
632
633 // override the startsubactivity call to make changes in state consistent.
634 @Override
635 public void startActivityForResult(Intent intent, int requestCode) {
636 if (requestCode == -1) {
637 // this is an intent requested from the preference framework.
638 super.startActivityForResult(intent, requestCode);
639 return;
640 }
641
642 if (DBG) log("startSubActivity: starting requested subactivity");
643 super.startActivityForResult(intent, requestCode);
644 }
645
646 private void switchToPreviousVoicemailProvider() {
647 if (DBG) log("switchToPreviousVoicemailProvider " + mPreviousVMProviderKey);
648 if (mPreviousVMProviderKey != null) {
649 if (mVMChangeCompletedSuccessfully || mFwdChangesRequireRollback) {
650 // we have to revert with carrier
651 if (DBG) {
652 log("Needs to rollback."
653 + " mVMChangeCompletedSuccessfully=" + mVMChangeCompletedSuccessfully
654 + ", mFwdChangesRequireRollback=" + mFwdChangesRequireRollback);
655 }
656
657 showDialogIfForeground(VOICEMAIL_REVERTING_DIALOG);
658 final VoiceMailProviderSettings prevSettings =
659 loadSettingsForVoiceMailProvider(mPreviousVMProviderKey);
660 if (prevSettings == null) {
661 // prevSettings never becomes null since it should be already loaded!
662 Log.e(LOG_TAG, "VoiceMailProviderSettings for the key \""
663 + mPreviousVMProviderKey + "\" becomes null, which is unexpected.");
664 if (DBG) {
665 Log.e(LOG_TAG,
666 "mVMChangeCompletedSuccessfully: " + mVMChangeCompletedSuccessfully
667 + ", mFwdChangesRequireRollback: " + mFwdChangesRequireRollback);
668 }
669 }
670 if (mVMChangeCompletedSuccessfully) {
671 mNewVMNumber = prevSettings.voicemailNumber;
672 Log.i(LOG_TAG, "VM change is already completed successfully."
673 + "Have to revert VM back to " + mNewVMNumber + " again.");
674 mPhone.setVoiceMailNumber(
675 mPhone.getVoiceMailAlphaTag().toString(),
676 mNewVMNumber,
677 Message.obtain(mRevertOptionComplete, EVENT_VOICEMAIL_CHANGED));
678 }
679 if (mFwdChangesRequireRollback) {
680 Log.i(LOG_TAG, "Requested to rollback Fwd changes.");
681 final CallForwardInfo[] prevFwdSettings =
682 prevSettings.forwardingSettings;
683 if (prevFwdSettings != null) {
684 Map<Integer, AsyncResult> results =
685 mForwardingChangeResults;
686 resetForwardingChangeState();
687 for (int i = 0; i < prevFwdSettings.length; i++) {
688 CallForwardInfo fi = prevFwdSettings[i];
689 if (DBG) log("Reverting fwd #: " + i + ": " + fi.toString());
690 // Only revert the settings for which the update
691 // succeeded
692 AsyncResult result = results.get(fi.reason);
693 if (result != null && result.exception == null) {
694 mExpectedChangeResultReasons.add(fi.reason);
695 mPhone.setCallForwardingOption(
696 (fi.status == 1 ?
697 CommandsInterface.CF_ACTION_REGISTRATION :
698 CommandsInterface.CF_ACTION_DISABLE),
699 fi.reason,
700 fi.number,
701 fi.timeSeconds,
702 mRevertOptionComplete.obtainMessage(
703 EVENT_FORWARDING_CHANGED, i, 0));
704 }
705 }
706 }
707 }
708 } else {
709 if (DBG) log("No need to revert");
710 onRevertDone();
711 }
712 }
713 }
714
715 private void onRevertDone() {
716 if (DBG) log("Flipping provider key back to " + mPreviousVMProviderKey);
717 mVoicemailProviders.setValue(mPreviousVMProviderKey);
718 updateVMPreferenceWidgets(mPreviousVMProviderKey);
719 updateVoiceNumberField();
720 if (mVMOrFwdSetError != 0) {
721 showVMDialog(mVMOrFwdSetError);
722 mVMOrFwdSetError = 0;
723 }
724 }
725
726 @Override
727 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
728 if (DBG) {
729 log("onActivityResult: requestCode: " + requestCode
730 + ", resultCode: " + resultCode
731 + ", data: " + data);
732 }
733 // there are cases where the contact picker may end up sending us more than one
734 // request. We want to ignore the request if we're not in the correct state.
735 if (requestCode == VOICEMAIL_PROVIDER_CFG_ID) {
736 boolean failure = false;
737
738 // No matter how the processing of result goes lets clear the flag
739 if (DBG) log("mVMProviderSettingsForced: " + mVMProviderSettingsForced);
740 final boolean isVMProviderSettingsForced = mVMProviderSettingsForced;
741 mVMProviderSettingsForced = false;
742
743 String vmNum = null;
744 if (resultCode != RESULT_OK) {
745 if (DBG) log("onActivityResult: vm provider cfg result not OK.");
746 failure = true;
747 } else {
748 if (data == null) {
749 if (DBG) log("onActivityResult: vm provider cfg result has no data");
750 failure = true;
751 } else {
752 if (data.getBooleanExtra(SIGNOUT_EXTRA, false)) {
753 if (DBG) log("Provider requested signout");
754 if (isVMProviderSettingsForced) {
755 if (DBG) log("Going back to previous provider on signout");
756 switchToPreviousVoicemailProvider();
757 } else {
758 final String victim = getCurrentVoicemailProviderKey();
759 if (DBG) log("Relaunching activity and ignoring " + victim);
760 Intent i = new Intent(ACTION_ADD_VOICEMAIL);
761 i.putExtra(IGNORE_PROVIDER_EXTRA, victim);
762 i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
763 this.startActivity(i);
764 }
765 return;
766 }
767 vmNum = data.getStringExtra(VM_NUMBER_EXTRA);
768 if (vmNum == null || vmNum.length() == 0) {
769 if (DBG) log("onActivityResult: vm provider cfg result has no vmnum");
770 failure = true;
771 }
772 }
773 }
774 if (failure) {
775 if (DBG) log("Failure in return from voicemail provider");
776 if (isVMProviderSettingsForced) {
777 switchToPreviousVoicemailProvider();
778 } else {
779 if (DBG) log("Not switching back the provider since this is not forced config");
780 }
781 return;
782 }
783 mChangingVMorFwdDueToProviderChange = isVMProviderSettingsForced;
784 final String fwdNum = data.getStringExtra(FWD_NUMBER_EXTRA);
785
Santos Cordonda120f42014-08-06 04:44:34 -0700786 // TODO: It would be nice to load the current network setting for this and
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700787 // send it to the provider when it's config is invoked so it can use this as default
788 final int fwdNumTime = data.getIntExtra(FWD_NUMBER_TIME_EXTRA, 20);
789
790 if (DBG) log("onActivityResult: vm provider cfg result " +
791 (fwdNum != null ? "has" : " does not have") + " forwarding number");
792 saveVoiceMailAndForwardingNumber(getCurrentVoicemailProviderKey(),
793 new VoiceMailProviderSettings(vmNum, fwdNum, fwdNumTime));
794 return;
795 }
796
797 if (requestCode == VOICEMAIL_PREF_ID) {
798 if (resultCode != RESULT_OK) {
799 if (DBG) log("onActivityResult: contact picker result not OK.");
800 return;
801 }
802
803 Cursor cursor = null;
804 try {
805 cursor = getContentResolver().query(data.getData(),
806 NUM_PROJECTION, null, null, null);
807 if ((cursor == null) || (!cursor.moveToFirst())) {
808 if (DBG) log("onActivityResult: bad contact data, no results found.");
809 return;
810 }
811 mSubMenuVoicemailSettings.onPickActivityResult(cursor.getString(0));
812 return;
813 } finally {
814 if (cursor != null) {
815 cursor.close();
816 }
817 }
818 }
819
820 super.onActivityResult(requestCode, resultCode, data);
821 }
822
823 // Voicemail button logic
824 private void handleVMBtnClickRequest() {
825 // normally called on the dialog close.
826
827 // Since we're stripping the formatting out on the getPhoneNumber()
828 // call now, we won't need to do so here anymore.
829
830 saveVoiceMailAndForwardingNumber(
831 getCurrentVoicemailProviderKey(),
832 new VoiceMailProviderSettings(mSubMenuVoicemailSettings.getPhoneNumber(),
Tyler Gunn4d45d1c2014-09-12 22:17:53 -0700833 FWD_SETTINGS_DONT_TOUCH)
834 );
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700835 }
836
837
838 /**
839 * Wrapper around showDialog() that will silently do nothing if we're
840 * not in the foreground.
841 *
842 * This is useful here because most of the dialogs we display from
843 * this class are triggered by asynchronous events (like
844 * success/failure messages from the telephony layer) and it's
845 * possible for those events to come in even after the user has gone
846 * to a different screen.
847 */
848 // TODO: this is too brittle: it's still easy to accidentally add new
849 // code here that calls showDialog() directly (which will result in a
850 // WindowManager$BadTokenException if called after the activity has
851 // been stopped.)
852 //
853 // It would be cleaner to do the "if (mForeground)" check in one
854 // central place, maybe by using a single Handler for all asynchronous
855 // events (and have *that* discard events if we're not in the
856 // foreground.)
857 //
858 // Unfortunately it's not that simple, since we sometimes need to do
859 // actual work to handle these events whether or not we're in the
860 // foreground (see the Handler code in mSetOptionComplete for
861 // example.)
862 private void showDialogIfForeground(int id) {
863 if (mForeground) {
864 showDialog(id);
865 }
866 }
867
868 private void dismissDialogSafely(int id) {
869 try {
870 dismissDialog(id);
871 } catch (IllegalArgumentException e) {
872 // This is expected in the case where we were in the background
873 // at the time we would normally have shown the dialog, so we didn't
874 // show it.
875 }
876 }
877
878 private void saveVoiceMailAndForwardingNumber(String key,
879 VoiceMailProviderSettings newSettings) {
880 if (DBG) log("saveVoiceMailAndForwardingNumber: " + newSettings.toString());
881 mNewVMNumber = newSettings.voicemailNumber;
882 // empty vm number == clearing the vm number ?
883 if (mNewVMNumber == null) {
884 mNewVMNumber = "";
885 }
886
887 mNewFwdSettings = newSettings.forwardingSettings;
888 if (DBG) log("newFwdNumber " +
889 String.valueOf((mNewFwdSettings != null ? mNewFwdSettings.length : 0))
890 + " settings");
891
892 // No fwd settings on CDMA
893 if (mPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
894 if (DBG) log("ignoring forwarding setting since this is CDMA phone");
895 mNewFwdSettings = FWD_SETTINGS_DONT_TOUCH;
896 }
897
898 //throw a warning if the vm is the same and we do not touch forwarding.
899 if (mNewVMNumber.equals(mOldVmNumber) && mNewFwdSettings == FWD_SETTINGS_DONT_TOUCH) {
900 showVMDialog(MSG_VM_NOCHANGE);
901 return;
902 }
903
904 maybeSaveSettingsForVoicemailProvider(key, newSettings);
905 mVMChangeCompletedSuccessfully = false;
906 mFwdChangesRequireRollback = false;
907 mVMOrFwdSetError = 0;
908 if (!key.equals(mPreviousVMProviderKey)) {
909 mReadingSettingsForDefaultProvider =
910 mPreviousVMProviderKey.equals(DEFAULT_VM_PROVIDER_KEY);
911 if (DBG) log("Reading current forwarding settings");
912 mForwardingReadResults = new CallForwardInfo[FORWARDING_SETTINGS_REASONS.length];
913 for (int i = 0; i < FORWARDING_SETTINGS_REASONS.length; i++) {
914 mForwardingReadResults[i] = null;
915 mPhone.getCallForwardingOption(FORWARDING_SETTINGS_REASONS[i],
916 mGetOptionComplete.obtainMessage(EVENT_FORWARDING_GET_COMPLETED, i, 0));
917 }
918 showDialogIfForeground(VOICEMAIL_FWD_READING_DIALOG);
919 } else {
920 saveVoiceMailAndForwardingNumberStage2();
921 }
922 }
923
924 private final Handler mGetOptionComplete = new Handler() {
925 @Override
926 public void handleMessage(Message msg) {
927 AsyncResult result = (AsyncResult) msg.obj;
928 switch (msg.what) {
929 case EVENT_FORWARDING_GET_COMPLETED:
930 handleForwardingSettingsReadResult(result, msg.arg1);
931 break;
932 }
933 }
934 };
935
936 private void handleForwardingSettingsReadResult(AsyncResult ar, int idx) {
937 if (DBG) Log.d(LOG_TAG, "handleForwardingSettingsReadResult: " + idx);
938 Throwable error = null;
939 if (ar.exception != null) {
940 if (DBG) Log.d(LOG_TAG, "FwdRead: ar.exception=" +
941 ar.exception.getMessage());
942 error = ar.exception;
943 }
944 if (ar.userObj instanceof Throwable) {
945 if (DBG) Log.d(LOG_TAG, "FwdRead: userObj=" +
946 ((Throwable)ar.userObj).getMessage());
947 error = (Throwable)ar.userObj;
948 }
949
950 // We may have already gotten an error and decided to ignore the other results.
951 if (mForwardingReadResults == null) {
952 if (DBG) Log.d(LOG_TAG, "ignoring fwd reading result: " + idx);
953 return;
954 }
955
956 // In case of error ignore other results, show an error dialog
957 if (error != null) {
958 if (DBG) Log.d(LOG_TAG, "Error discovered for fwd read : " + idx);
959 mForwardingReadResults = null;
960 dismissDialogSafely(VOICEMAIL_FWD_READING_DIALOG);
961 showVMDialog(MSG_FW_GET_EXCEPTION);
962 return;
963 }
964
965 // Get the forwarding info
966 final CallForwardInfo cfInfoArray[] = (CallForwardInfo[]) ar.result;
967 CallForwardInfo fi = null;
968 for (int i = 0 ; i < cfInfoArray.length; i++) {
969 if ((cfInfoArray[i].serviceClass & CommandsInterface.SERVICE_CLASS_VOICE) != 0) {
970 fi = cfInfoArray[i];
971 break;
972 }
973 }
974 if (fi == null) {
975
976 // In case we go nothing it means we need this reason disabled
977 // so create a CallForwardInfo for capturing this
978 if (DBG) Log.d(LOG_TAG, "Creating default info for " + idx);
979 fi = new CallForwardInfo();
980 fi.status = 0;
981 fi.reason = FORWARDING_SETTINGS_REASONS[idx];
982 fi.serviceClass = CommandsInterface.SERVICE_CLASS_VOICE;
983 } else {
984 // if there is not a forwarding number, ensure the entry is set to "not active."
985 if (fi.number == null || fi.number.length() == 0) {
986 fi.status = 0;
987 }
988
989 if (DBG) Log.d(LOG_TAG, "Got " + fi.toString() + " for " + idx);
990 }
991 mForwardingReadResults[idx] = fi;
992
993 // Check if we got all the results already
994 boolean done = true;
995 for (int i = 0; i < mForwardingReadResults.length; i++) {
996 if (mForwardingReadResults[i] == null) {
997 done = false;
998 break;
999 }
1000 }
1001 if (done) {
1002 if (DBG) Log.d(LOG_TAG, "Done receiving fwd info");
1003 dismissDialogSafely(VOICEMAIL_FWD_READING_DIALOG);
1004 if (mReadingSettingsForDefaultProvider) {
1005 maybeSaveSettingsForVoicemailProvider(DEFAULT_VM_PROVIDER_KEY,
1006 new VoiceMailProviderSettings(this.mOldVmNumber,
1007 mForwardingReadResults));
1008 mReadingSettingsForDefaultProvider = false;
1009 }
1010 saveVoiceMailAndForwardingNumberStage2();
1011 } else {
1012 if (DBG) Log.d(LOG_TAG, "Not done receiving fwd info");
1013 }
1014 }
1015
1016 private CallForwardInfo infoForReason(CallForwardInfo[] infos, int reason) {
1017 CallForwardInfo result = null;
1018 if (null != infos) {
1019 for (CallForwardInfo info : infos) {
1020 if (info.reason == reason) {
1021 result = info;
1022 break;
1023 }
1024 }
1025 }
1026 return result;
1027 }
1028
1029 private boolean isUpdateRequired(CallForwardInfo oldInfo,
1030 CallForwardInfo newInfo) {
1031 boolean result = true;
1032 if (0 == newInfo.status) {
1033 // If we're disabling a type of forwarding, and it's already
1034 // disabled for the account, don't make any change
1035 if (oldInfo != null && oldInfo.status == 0) {
1036 result = false;
1037 }
1038 }
1039 return result;
1040 }
1041
1042 private void resetForwardingChangeState() {
1043 mForwardingChangeResults = new HashMap<Integer, AsyncResult>();
1044 mExpectedChangeResultReasons = new HashSet<Integer>();
1045 }
1046
1047 // Called after we are done saving the previous forwarding settings if
1048 // we needed.
1049 private void saveVoiceMailAndForwardingNumberStage2() {
1050 mForwardingChangeResults = null;
1051 mVoicemailChangeResult = null;
1052 if (mNewFwdSettings != FWD_SETTINGS_DONT_TOUCH) {
1053 resetForwardingChangeState();
1054 for (int i = 0; i < mNewFwdSettings.length; i++) {
1055 CallForwardInfo fi = mNewFwdSettings[i];
1056
1057 final boolean doUpdate = isUpdateRequired(infoForReason(
1058 mForwardingReadResults, fi.reason), fi);
1059
1060 if (doUpdate) {
1061 if (DBG) log("Setting fwd #: " + i + ": " + fi.toString());
1062 mExpectedChangeResultReasons.add(i);
1063
1064 mPhone.setCallForwardingOption(
1065 fi.status == 1 ?
1066 CommandsInterface.CF_ACTION_REGISTRATION :
1067 CommandsInterface.CF_ACTION_DISABLE,
1068 fi.reason,
1069 fi.number,
1070 fi.timeSeconds,
1071 mSetOptionComplete.obtainMessage(
1072 EVENT_FORWARDING_CHANGED, fi.reason, 0));
1073 }
1074 }
1075 showDialogIfForeground(VOICEMAIL_FWD_SAVING_DIALOG);
1076 } else {
1077 if (DBG) log("Not touching fwd #");
1078 setVMNumberWithCarrier();
1079 }
1080 }
1081
1082 private void setVMNumberWithCarrier() {
1083 if (DBG) log("save voicemail #: " + mNewVMNumber);
1084 mPhone.setVoiceMailNumber(
1085 mPhone.getVoiceMailAlphaTag().toString(),
1086 mNewVMNumber,
1087 Message.obtain(mSetOptionComplete, EVENT_VOICEMAIL_CHANGED));
1088 }
1089
1090 /**
1091 * Callback to handle option update completions
1092 */
1093 private final Handler mSetOptionComplete = new Handler() {
1094 @Override
1095 public void handleMessage(Message msg) {
1096 AsyncResult result = (AsyncResult) msg.obj;
1097 boolean done = false;
1098 switch (msg.what) {
1099 case EVENT_VOICEMAIL_CHANGED:
1100 mVoicemailChangeResult = result;
1101 mVMChangeCompletedSuccessfully = checkVMChangeSuccess() == null;
1102 if (DBG) log("VM change complete msg, VM change done = " +
1103 String.valueOf(mVMChangeCompletedSuccessfully));
1104 done = true;
1105 break;
1106 case EVENT_FORWARDING_CHANGED:
1107 mForwardingChangeResults.put(msg.arg1, result);
1108 if (result.exception != null) {
1109 Log.w(LOG_TAG, "Error in setting fwd# " + msg.arg1 + ": " +
1110 result.exception.getMessage());
1111 } else {
1112 if (DBG) log("Success in setting fwd# " + msg.arg1);
1113 }
1114 final boolean completed = checkForwardingCompleted();
1115 if (completed) {
1116 if (checkFwdChangeSuccess() == null) {
1117 if (DBG) log("Overall fwd changes completed ok, starting vm change");
1118 setVMNumberWithCarrier();
1119 } else {
1120 Log.w(LOG_TAG, "Overall fwd changes completed in failure. " +
1121 "Check if we need to try rollback for some settings.");
1122 mFwdChangesRequireRollback = false;
1123 Iterator<Map.Entry<Integer,AsyncResult>> it =
1124 mForwardingChangeResults.entrySet().iterator();
1125 while (it.hasNext()) {
1126 Map.Entry<Integer,AsyncResult> entry = it.next();
1127 if (entry.getValue().exception == null) {
1128 // If at least one succeeded we have to revert
1129 Log.i(LOG_TAG, "Rollback will be required");
1130 mFwdChangesRequireRollback = true;
1131 break;
1132 }
1133 }
1134 if (!mFwdChangesRequireRollback) {
1135 Log.i(LOG_TAG, "No rollback needed.");
1136 }
1137 done = true;
1138 }
1139 }
1140 break;
1141 default:
1142 // TODO: should never reach this, may want to throw exception
1143 }
1144 if (done) {
1145 if (DBG) log("All VM provider related changes done");
1146 if (mForwardingChangeResults != null) {
1147 dismissDialogSafely(VOICEMAIL_FWD_SAVING_DIALOG);
1148 }
1149 handleSetVMOrFwdMessage();
1150 }
1151 }
1152 };
1153
1154 /**
1155 * Callback to handle option revert completions
1156 */
1157 private final Handler mRevertOptionComplete = new Handler() {
1158 @Override
1159 public void handleMessage(Message msg) {
1160 AsyncResult result = (AsyncResult) msg.obj;
1161 switch (msg.what) {
1162 case EVENT_VOICEMAIL_CHANGED:
1163 mVoicemailChangeResult = result;
1164 if (DBG) log("VM revert complete msg");
1165 break;
1166 case EVENT_FORWARDING_CHANGED:
1167 mForwardingChangeResults.put(msg.arg1, result);
1168 if (result.exception != null) {
1169 if (DBG) log("Error in reverting fwd# " + msg.arg1 + ": " +
1170 result.exception.getMessage());
1171 } else {
1172 if (DBG) log("Success in reverting fwd# " + msg.arg1);
1173 }
1174 if (DBG) log("FWD revert complete msg ");
1175 break;
1176 default:
1177 // TODO: should never reach this, may want to throw exception
1178 }
1179 final boolean done =
1180 (!mVMChangeCompletedSuccessfully || mVoicemailChangeResult != null) &&
1181 (!mFwdChangesRequireRollback || checkForwardingCompleted());
1182 if (done) {
1183 if (DBG) log("All VM reverts done");
1184 dismissDialogSafely(VOICEMAIL_REVERTING_DIALOG);
1185 onRevertDone();
1186 }
1187 }
1188 };
1189
1190 /**
1191 * @return true if forwarding change has completed
1192 */
1193 private boolean checkForwardingCompleted() {
1194 boolean result;
1195 if (mForwardingChangeResults == null) {
1196 result = true;
1197 } else {
1198 // return true iff there is a change result for every reason for
1199 // which we expected a result
1200 result = true;
1201 for (Integer reason : mExpectedChangeResultReasons) {
1202 if (mForwardingChangeResults.get(reason) == null) {
1203 result = false;
1204 break;
1205 }
1206 }
1207 }
1208 return result;
1209 }
1210 /**
1211 * @return error string or null if successful
1212 */
1213 private String checkFwdChangeSuccess() {
1214 String result = null;
1215 Iterator<Map.Entry<Integer,AsyncResult>> it =
1216 mForwardingChangeResults.entrySet().iterator();
1217 while (it.hasNext()) {
1218 Map.Entry<Integer,AsyncResult> entry = it.next();
1219 Throwable exception = entry.getValue().exception;
1220 if (exception != null) {
1221 result = exception.getMessage();
1222 if (result == null) {
1223 result = "";
1224 }
1225 break;
1226 }
1227 }
1228 return result;
1229 }
1230
1231 /**
1232 * @return error string or null if successful
1233 */
1234 private String checkVMChangeSuccess() {
1235 if (mVoicemailChangeResult.exception != null) {
1236 final String msg = mVoicemailChangeResult.exception.getMessage();
1237 if (msg == null) {
1238 return "";
1239 }
1240 return msg;
1241 }
1242 return null;
1243 }
1244
1245 private void handleSetVMOrFwdMessage() {
1246 if (DBG) {
1247 log("handleSetVMMessage: set VM request complete");
1248 }
1249 boolean success = true;
1250 boolean fwdFailure = false;
1251 String exceptionMessage = "";
1252 if (mForwardingChangeResults != null) {
1253 exceptionMessage = checkFwdChangeSuccess();
1254 if (exceptionMessage != null) {
1255 success = false;
1256 fwdFailure = true;
1257 }
1258 }
1259 if (success) {
1260 exceptionMessage = checkVMChangeSuccess();
1261 if (exceptionMessage != null) {
1262 success = false;
1263 }
1264 }
1265 if (success) {
1266 if (DBG) log("change VM success!");
1267 handleVMAndFwdSetSuccess(MSG_VM_OK);
1268 } else {
1269 if (fwdFailure) {
1270 Log.w(LOG_TAG, "Failed to change fowarding setting. Reason: " + exceptionMessage);
1271 handleVMOrFwdSetError(MSG_FW_SET_EXCEPTION);
1272 } else {
1273 Log.w(LOG_TAG, "Failed to change voicemail. Reason: " + exceptionMessage);
1274 handleVMOrFwdSetError(MSG_VM_EXCEPTION);
1275 }
1276 }
1277 }
1278
1279 /**
1280 * Called when Voicemail Provider or its forwarding settings failed. Rolls back partly made
1281 * changes to those settings and show "failure" dialog.
1282 *
1283 * @param msgId Message ID used for the specific error case. {@link #MSG_FW_SET_EXCEPTION} or
1284 * {@link #MSG_VM_EXCEPTION}
1285 */
1286 private void handleVMOrFwdSetError(int msgId) {
1287 if (mChangingVMorFwdDueToProviderChange) {
1288 mVMOrFwdSetError = msgId;
1289 mChangingVMorFwdDueToProviderChange = false;
1290 switchToPreviousVoicemailProvider();
1291 return;
1292 }
1293 mChangingVMorFwdDueToProviderChange = false;
1294 showVMDialog(msgId);
1295 updateVoiceNumberField();
1296 }
1297
1298 /**
1299 * Called when Voicemail Provider and its forwarding settings were successfully finished.
1300 * This updates a bunch of variables and show "success" dialog.
1301 */
1302 private void handleVMAndFwdSetSuccess(int msg) {
1303 if (DBG) {
1304 log("handleVMAndFwdSetSuccess(). current voicemail provider key: "
1305 + getCurrentVoicemailProviderKey());
1306 }
1307 mPreviousVMProviderKey = getCurrentVoicemailProviderKey();
1308 mChangingVMorFwdDueToProviderChange = false;
1309 showVMDialog(msg);
1310 updateVoiceNumberField();
1311 }
1312
1313 /**
1314 * Update the voicemail number from what we've recorded on the sim.
1315 */
1316 private void updateVoiceNumberField() {
1317 if (DBG) {
1318 log("updateVoiceNumberField(). mSubMenuVoicemailSettings=" + mSubMenuVoicemailSettings);
1319 }
1320 if (mSubMenuVoicemailSettings == null) {
1321 return;
1322 }
1323
1324 mOldVmNumber = mPhone.getVoiceMailNumber();
1325 if (mOldVmNumber == null) {
1326 mOldVmNumber = "";
1327 }
1328 mSubMenuVoicemailSettings.setPhoneNumber(mOldVmNumber);
1329 final String summary = (mOldVmNumber.length() > 0) ? mOldVmNumber :
1330 getString(R.string.voicemail_number_not_set);
1331 mSubMenuVoicemailSettings.setSummary(summary);
1332 }
1333
1334 /*
1335 * Helper Methods for Activity class.
1336 * The initial query commands are split into two pieces now
1337 * for individual expansion. This combined with the ability
1338 * to cancel queries allows for a much better user experience,
1339 * and also ensures that the user only waits to update the
1340 * data that is relevant.
1341 */
1342
1343 @Override
1344 protected void onPrepareDialog(int id, Dialog dialog) {
1345 super.onPrepareDialog(id, dialog);
1346 mCurrentDialogId = id;
1347 }
1348
1349 // dialog creation method, called by showDialog()
1350 @Override
1351 protected Dialog onCreateDialog(int id) {
1352 if ((id == VM_RESPONSE_ERROR) || (id == VM_NOCHANGE_ERROR) ||
1353 (id == FW_SET_RESPONSE_ERROR) || (id == FW_GET_RESPONSE_ERROR) ||
1354 (id == VOICEMAIL_DIALOG_CONFIRM)) {
1355
1356 AlertDialog.Builder b = new AlertDialog.Builder(this);
1357
1358 int msgId;
1359 int titleId = R.string.error_updating_title;
1360 switch (id) {
1361 case VOICEMAIL_DIALOG_CONFIRM:
1362 msgId = R.string.vm_changed;
1363 titleId = R.string.voicemail;
1364 // Set Button 2
1365 b.setNegativeButton(R.string.close_dialog, this);
1366 break;
1367 case VM_NOCHANGE_ERROR:
1368 // even though this is technically an error,
1369 // keep the title friendly.
1370 msgId = R.string.no_change;
1371 titleId = R.string.voicemail;
1372 // Set Button 2
1373 b.setNegativeButton(R.string.close_dialog, this);
1374 break;
1375 case VM_RESPONSE_ERROR:
1376 msgId = R.string.vm_change_failed;
1377 // Set Button 1
1378 b.setPositiveButton(R.string.close_dialog, this);
1379 break;
1380 case FW_SET_RESPONSE_ERROR:
1381 msgId = R.string.fw_change_failed;
1382 // Set Button 1
1383 b.setPositiveButton(R.string.close_dialog, this);
1384 break;
1385 case FW_GET_RESPONSE_ERROR:
1386 msgId = R.string.fw_get_in_vm_failed;
1387 b.setPositiveButton(R.string.alert_dialog_yes, this);
1388 b.setNegativeButton(R.string.alert_dialog_no, this);
1389 break;
1390 default:
1391 msgId = R.string.exception_error;
1392 // Set Button 3, tells the activity that the error is
1393 // not recoverable on dialog exit.
1394 b.setNeutralButton(R.string.close_dialog, this);
1395 break;
1396 }
1397
1398 b.setTitle(getText(titleId));
1399 String message = getText(msgId).toString();
1400 b.setMessage(message);
1401 b.setCancelable(false);
1402 AlertDialog dialog = b.create();
1403
1404 // make the dialog more obvious by bluring the background.
1405 dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
1406
1407 return dialog;
1408 } else if (id == VOICEMAIL_FWD_SAVING_DIALOG || id == VOICEMAIL_FWD_READING_DIALOG ||
1409 id == VOICEMAIL_REVERTING_DIALOG) {
1410 ProgressDialog dialog = new ProgressDialog(this);
1411 dialog.setTitle(getText(R.string.updating_title));
1412 dialog.setIndeterminate(true);
1413 dialog.setCancelable(false);
1414 dialog.setMessage(getText(
1415 id == VOICEMAIL_FWD_SAVING_DIALOG ? R.string.updating_settings :
1416 (id == VOICEMAIL_REVERTING_DIALOG ? R.string.reverting_settings :
1417 R.string.reading_settings)));
1418 return dialog;
1419 }
1420
1421
1422 return null;
1423 }
1424
1425 // This is a method implemented for DialogInterface.OnClickListener.
1426 // Used with the error dialog to close the app, voicemail dialog to just dismiss.
1427 // Close button is mapped to BUTTON_POSITIVE for the errors that close the activity,
1428 // while those that are mapped to BUTTON_NEUTRAL only move the preference focus.
1429 public void onClick(DialogInterface dialog, int which) {
1430 dialog.dismiss();
1431 switch (which){
1432 case DialogInterface.BUTTON_NEUTRAL:
1433 if (DBG) log("Neutral button");
1434 break;
1435 case DialogInterface.BUTTON_NEGATIVE:
1436 if (DBG) log("Negative button");
1437 if (mCurrentDialogId == FW_GET_RESPONSE_ERROR) {
1438 // We failed to get current forwarding settings and the user
1439 // does not wish to continue.
1440 switchToPreviousVoicemailProvider();
1441 }
1442 break;
1443 case DialogInterface.BUTTON_POSITIVE:
1444 if (DBG) log("Positive button");
1445 if (mCurrentDialogId == FW_GET_RESPONSE_ERROR) {
1446 // We failed to get current forwarding settings but the user
1447 // wishes to continue changing settings to the new vm provider
1448 saveVoiceMailAndForwardingNumberStage2();
1449 } else {
1450 finish();
1451 }
1452 return;
1453 default:
1454 // just let the dialog close and go back to the input
1455 }
1456 // In all dialogs, all buttons except BUTTON_POSITIVE lead to the end of user interaction
1457 // with settings UI. If we were called to explicitly configure voice mail then
1458 // we finish the settings activity here to come back to whatever the user was doing.
1459 if (getIntent().getAction().equals(ACTION_ADD_VOICEMAIL)) {
1460 finish();
1461 }
1462 }
1463
1464 // set the app state with optional status.
1465 private void showVMDialog(int msgStatus) {
1466 switch (msgStatus) {
1467 // It's a bit worrisome to punt in the error cases here when we're
1468 // not in the foreground; maybe toast instead?
1469 case MSG_VM_EXCEPTION:
1470 showDialogIfForeground(VM_RESPONSE_ERROR);
1471 break;
1472 case MSG_FW_SET_EXCEPTION:
1473 showDialogIfForeground(FW_SET_RESPONSE_ERROR);
1474 break;
1475 case MSG_FW_GET_EXCEPTION:
1476 showDialogIfForeground(FW_GET_RESPONSE_ERROR);
1477 break;
1478 case MSG_VM_NOCHANGE:
1479 showDialogIfForeground(VM_NOCHANGE_ERROR);
1480 break;
1481 case MSG_VM_OK:
1482 showDialogIfForeground(VOICEMAIL_DIALOG_CONFIRM);
1483 break;
1484 case MSG_OK:
1485 default:
1486 // This should never happen.
1487 }
1488 }
1489
1490 /*
1491 * Activity class methods
1492 */
1493
1494 @Override
1495 protected void onCreate(Bundle icicle) {
1496 super.onCreate(icicle);
1497 if (DBG) log("onCreate(). Intent: " + getIntent());
1498 mPhone = PhoneGlobals.getPhone();
Tyler Gunnbaee2952014-09-10 16:01:02 -07001499 mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
1500
1501 // create intent to bring up contact list
1502 mContactListIntent = new Intent(Intent.ACTION_GET_CONTENT);
1503 mContactListIntent.setType(android.provider.Contacts.Phones.CONTENT_ITEM_TYPE);
1504
1505 mVoicemailRingtoneLookupRunnable = new Runnable() {
1506 @Override
1507 public void run() {
1508 if (mVoicemailNotificationRingtone != null) {
1509 SettingsUtil.updateRingtoneName(
1510 mPhone.getContext(),
1511 mVoicemailRingtoneLookupComplete,
1512 RingtoneManager.TYPE_NOTIFICATION,
1513 mVoicemailNotificationRingtone,
1514 MSG_UPDATE_VOICEMAIL_RINGTONE_SUMMARY);
1515 }
1516 }
1517 };
1518
Tyler Gunnbaee2952014-09-10 16:01:02 -07001519 // Show the voicemail preference in onResume if the calling intent specifies the
1520 // ACTION_ADD_VOICEMAIL action.
1521 mShowVoicemailPreference = (icicle == null) &&
1522 getIntent().getAction().equals(ACTION_ADD_VOICEMAIL);
1523 }
1524
1525 private void initPhoneAccountPreferences() {
Andrew Leece8ae2a2014-09-10 10:41:48 -07001526 mPhoneAccountSettingsPreference = findPreference(PHONE_ACCOUNT_SETTINGS_KEY);
Tyler Gunnbaee2952014-09-10 16:01:02 -07001527
Tyler Gunn4d45d1c2014-09-12 22:17:53 -07001528 TelecomManager telecomManager = TelecomManager.from(this);
Tyler Gunnbaee2952014-09-10 16:01:02 -07001529
Andrew Leece8ae2a2014-09-10 10:41:48 -07001530 if (telecomManager.getAllPhoneAccountsCount() <= 1
1531 && telecomManager.getSimCallManagers().isEmpty()
1532 && !SipUtil.isVoipSupported(this)) {
1533 getPreferenceScreen().removePreference(mPhoneAccountSettingsPreference);
Tyler Gunnbaee2952014-09-10 16:01:02 -07001534 }
1535 }
1536
1537 private boolean canLaunchIntent(Intent intent) {
1538 PackageManager pm = getPackageManager();
1539 return pm.resolveActivity(intent, PackageManager.GET_ACTIVITIES) != null;
1540 }
1541
Tyler Gunnbaee2952014-09-10 16:01:02 -07001542 @Override
1543 protected void onResume() {
1544 super.onResume();
1545 mForeground = true;
1546
1547 PreferenceScreen preferenceScreen = getPreferenceScreen();
1548 if (preferenceScreen != null) {
1549 preferenceScreen.removeAll();
1550 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001551
1552 addPreferencesFromResource(R.xml.call_feature_setting);
Andrew Leedb2fe562014-09-03 15:40:43 -07001553 initPhoneAccountPreferences();
1554
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001555 // get buttons
1556 PreferenceScreen prefSet = getPreferenceScreen();
Andrew Lee64a7d792014-10-15 17:38:38 -07001557 mSubMenuVoicemailSettings = (EditPhoneNumberPreference) findPreference(BUTTON_VOICEMAIL_KEY);
1558 mSubMenuVoicemailSettings.setParentActivity(this, VOICEMAIL_PREF_ID, this);
1559 mSubMenuVoicemailSettings.setDialogOnClosedListener(this);
1560 mSubMenuVoicemailSettings.setDialogTitle(R.string.voicemail_settings_number_label);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001561
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001562 mButtonDTMF = (ListPreference) findPreference(BUTTON_DTMF_KEY);
1563 mButtonAutoRetry = (CheckBoxPreference) findPreference(BUTTON_RETRY_KEY);
1564 mButtonHAC = (CheckBoxPreference) findPreference(BUTTON_HAC_KEY);
1565 mButtonTTY = (ListPreference) findPreference(BUTTON_TTY_KEY);
1566 mVoicemailProviders = (ListPreference) findPreference(BUTTON_VOICEMAIL_PROVIDER_KEY);
Andrew Leedf14ead2014-10-17 14:22:52 -07001567 CheckBoxPreference mEnableVideoCalling =
1568 (CheckBoxPreference) findPreference(ENABLE_VIDEO_CALLING_KEY);
Andrew Lee2170a972014-08-13 18:13:01 -07001569
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001570 if (mVoicemailProviders != null) {
1571 mVoicemailProviders.setOnPreferenceChangeListener(this);
Andrew Lee97708a42014-09-25 12:39:07 -07001572 mVoicemailSettingsScreen =
1573 (PreferenceScreen) findPreference(VOICEMAIL_SETTING_SCREEN_PREF_KEY);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001574 mVoicemailSettings = (PreferenceScreen)findPreference(BUTTON_VOICEMAIL_SETTING_KEY);
1575 mVoicemailNotificationRingtone =
1576 findPreference(BUTTON_VOICEMAIL_NOTIFICATION_RINGTONE_KEY);
1577 mVoicemailNotificationVibrate =
1578 (CheckBoxPreference) findPreference(BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY);
1579 initVoiceMailProviders();
1580 }
1581
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001582
Andrew Lee64a7d792014-10-15 17:38:38 -07001583 if (getResources().getBoolean(R.bool.dtmf_type_enabled)) {
1584 mButtonDTMF.setOnPreferenceChangeListener(this);
1585 int dtmf = Settings.System.getInt(getContentResolver(),
1586 Settings.System.DTMF_TONE_TYPE_WHEN_DIALING, Constants.DTMF_TONE_TYPE_NORMAL);
1587 mButtonDTMF.setValueIndex(dtmf);
1588 } else {
1589 prefSet.removePreference(mButtonDTMF);
1590 mButtonDTMF = null;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001591 }
1592
Andrew Lee64a7d792014-10-15 17:38:38 -07001593 if (getResources().getBoolean(R.bool.auto_retry_enabled)) {
1594 mButtonAutoRetry.setOnPreferenceChangeListener(this);
1595 int autoretry = Settings.Global.getInt(
1596 getContentResolver(), Settings.Global.CALL_AUTO_RETRY, 0);
1597 mButtonAutoRetry.setChecked(autoretry != 0);
1598 } else {
1599 prefSet.removePreference(mButtonAutoRetry);
1600 mButtonAutoRetry = null;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001601 }
1602
Andrew Lee64a7d792014-10-15 17:38:38 -07001603 if (getResources().getBoolean(R.bool.hac_enabled)) {
1604 mButtonHAC.setOnPreferenceChangeListener(this);
1605 int hac = Settings.System.getInt(getContentResolver(), Settings.System.HEARING_AID, 0);
1606 mButtonHAC.setChecked(hac != 0);
1607 } else {
1608 prefSet.removePreference(mButtonHAC);
1609 mButtonHAC = null;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001610 }
1611
Andrew Lee64a7d792014-10-15 17:38:38 -07001612 TelecomManager telecomManager = TelecomManager.from(this);
1613 if (telecomManager != null && telecomManager.isTtySupported()) {
1614 mButtonTTY.setOnPreferenceChangeListener(this);
1615 int settingsTtyMode = Settings.Secure.getInt(getContentResolver(),
1616 Settings.Secure.PREFERRED_TTY_MODE,
1617 TelecomManager.TTY_MODE_OFF);
1618 mButtonTTY.setValue(Integer.toString(settingsTtyMode));
1619 updatePreferredTtyModeSummary(settingsTtyMode);
1620 } else {
1621 prefSet.removePreference(mButtonTTY);
1622 mButtonTTY = null;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001623 }
1624
1625 if (!getResources().getBoolean(R.bool.world_phone)) {
1626 Preference options = prefSet.findPreference(BUTTON_CDMA_OPTIONS);
Andrew Lee2170a972014-08-13 18:13:01 -07001627 if (options != null) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001628 prefSet.removePreference(options);
Andrew Lee2170a972014-08-13 18:13:01 -07001629 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001630 options = prefSet.findPreference(BUTTON_GSM_UMTS_OPTIONS);
Andrew Lee2170a972014-08-13 18:13:01 -07001631 if (options != null) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001632 prefSet.removePreference(options);
Andrew Lee2170a972014-08-13 18:13:01 -07001633 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001634
1635 int phoneType = mPhone.getPhoneType();
1636 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1637 Preference fdnButton = prefSet.findPreference(BUTTON_FDN_KEY);
Andrew Lee2170a972014-08-13 18:13:01 -07001638 if (fdnButton != null) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001639 prefSet.removePreference(fdnButton);
Andrew Lee2170a972014-08-13 18:13:01 -07001640 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001641 if (!getResources().getBoolean(R.bool.config_voice_privacy_disable)) {
1642 addPreferencesFromResource(R.xml.cdma_call_privacy);
1643 }
1644 } else if (phoneType == PhoneConstants.PHONE_TYPE_GSM) {
Andrew Lee2170a972014-08-13 18:13:01 -07001645 if (getResources().getBoolean(R.bool.config_additional_call_setting)) {
Etan Cohen0ca1c802014-07-07 15:35:48 -07001646 addPreferencesFromResource(R.xml.gsm_umts_call_options);
1647 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001648 } else {
1649 throw new IllegalStateException("Unexpected phone type: " + phoneType);
1650 }
1651 }
1652
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001653 // check the intent that started this activity and pop up the voicemail
1654 // dialog if we've been asked to.
1655 // If we have at least one non default VM provider registered then bring up
1656 // the selection for the VM provider, otherwise bring up a VM number dialog.
1657 // We only bring up the dialog the first time we are called (not after orientation change)
Tyler Gunnbaee2952014-09-10 16:01:02 -07001658 if (mShowVoicemailPreference && mVoicemailProviders != null) {
1659 if (DBG) {
1660 log("ACTION_ADD_VOICEMAIL Intent is thrown. current VM data size: "
1661 + mVMProvidersData.size());
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001662 }
Tyler Gunnbaee2952014-09-10 16:01:02 -07001663 if (mVMProvidersData.size() > 1) {
1664 simulatePreferenceClick(mVoicemailProviders);
1665 } else {
1666 onPreferenceChange(mVoicemailProviders, DEFAULT_VM_PROVIDER_KEY);
1667 mVoicemailProviders.setValue(DEFAULT_VM_PROVIDER_KEY);
1668 }
1669 mShowVoicemailPreference = false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001670 }
Tyler Gunnbaee2952014-09-10 16:01:02 -07001671
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001672 updateVoiceNumberField();
1673 mVMProviderSettingsForced = false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001674
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001675 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(
1676 mPhone.getContext());
1677 if (migrateVoicemailVibrationSettingsIfNeeded(prefs)) {
1678 mVoicemailNotificationVibrate.setChecked(prefs.getBoolean(
1679 BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY, false));
1680 }
1681
Andrew Lee77527ac2014-10-21 16:57:39 -07001682 if (ImsUtil.isImsEnabled(mPhone.getContext()) && ENABLE_VT_FLAG) {
1683 mEnableVideoCalling.setChecked(
1684 PhoneGlobals.getInstance().phoneMgr.isVideoCallingEnabled());
1685 mEnableVideoCalling.setOnPreferenceChangeListener(this);
1686 } else {
1687 prefSet.removePreference(mEnableVideoCalling);
1688 }
Andrew Leedf14ead2014-10-17 14:22:52 -07001689
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}