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