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