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