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