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