blob: 289767d3fc0214457651f90422999334479d96d7 [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;
52import android.preference.PreferenceGroup;
53import android.preference.PreferenceManager;
54import android.preference.PreferenceScreen;
55import android.provider.ContactsContract.CommonDataKinds;
56import android.provider.MediaStore;
57import android.provider.Settings;
Ihab Awad098f2d72014-05-19 17:34:52 -070058import android.telecomm.TelecommConstants;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070059import android.telephony.PhoneNumberUtils;
60import android.text.TextUtils;
61import android.util.Log;
62import android.view.MenuItem;
63import android.view.WindowManager;
64import android.widget.ListAdapter;
65
66import com.android.internal.telephony.CallForwardInfo;
67import com.android.internal.telephony.CommandsInterface;
68import com.android.internal.telephony.Phone;
69import com.android.internal.telephony.PhoneConstants;
70import com.android.internal.telephony.cdma.TtyIntent;
71import com.android.phone.sip.SipSharedPreferences;
72
73import java.util.Collection;
74import java.util.HashMap;
75import java.util.HashSet;
76import java.util.Iterator;
77import java.util.List;
78import java.util.Map;
79
80/**
81 * Top level "Call settings" UI; see res/xml/call_feature_setting.xml
82 *
83 * This preference screen is the root of the "Call settings" hierarchy
84 * available from the Phone app; the settings here let you control various
85 * features related to phone calls (including voicemail settings, SIP
86 * settings, the "Respond via SMS" feature, and others.) It's used only
87 * on voice-capable phone devices.
88 *
89 * Note that this activity is part of the package com.android.phone, even
90 * though you reach it from the "Phone" app (i.e. DialtactsActivity) which
91 * is from the package com.android.contacts.
92 *
93 * For the "Mobile network settings" screen under the main Settings app,
94 * See {@link MobileNetworkSettings}.
95 *
96 * @see com.android.phone.MobileNetworkSettings
97 */
98public class CallFeaturesSetting extends PreferenceActivity
99 implements DialogInterface.OnClickListener,
100 Preference.OnPreferenceChangeListener,
Evan Charlton1c696832014-04-15 14:24:23 -0700101 Preference.OnPreferenceClickListener,
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700102 EditPhoneNumberPreference.OnDialogClosedListener,
Evan Charlton1c696832014-04-15 14:24:23 -0700103 EditPhoneNumberPreference.GetDefaultNumberListener {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700104 private static final String LOG_TAG = "CallFeaturesSetting";
105 private static final boolean DBG = (PhoneGlobals.DBG_LEVEL >= 2);
106
107 /**
108 * Intent action to bring up Voicemail Provider settings.
109 *
110 * @see #IGNORE_PROVIDER_EXTRA
111 */
112 public static final String ACTION_ADD_VOICEMAIL =
113 "com.android.phone.CallFeaturesSetting.ADD_VOICEMAIL";
114 // intent action sent by this activity to a voice mail provider
115 // to trigger its configuration UI
116 public static final String ACTION_CONFIGURE_VOICEMAIL =
117 "com.android.phone.CallFeaturesSetting.CONFIGURE_VOICEMAIL";
118 // Extra put in the return from VM provider config containing voicemail number to set
119 public static final String VM_NUMBER_EXTRA = "com.android.phone.VoicemailNumber";
120 // Extra put in the return from VM provider config containing call forwarding number to set
121 public static final String FWD_NUMBER_EXTRA = "com.android.phone.ForwardingNumber";
122 // Extra put in the return from VM provider config containing call forwarding number to set
123 public static final String FWD_NUMBER_TIME_EXTRA = "com.android.phone.ForwardingNumberTime";
124 // If the VM provider returns non null value in this extra we will force the user to
125 // choose another VM provider
126 public static final String SIGNOUT_EXTRA = "com.android.phone.Signout";
127 //Information about logical "up" Activity
128 private static final String UP_ACTIVITY_PACKAGE = "com.android.dialer";
129 private static final String UP_ACTIVITY_CLASS =
130 "com.android.dialer.DialtactsActivity";
131
132 // Used to tell the saving logic to leave forwarding number as is
133 public static final CallForwardInfo[] FWD_SETTINGS_DONT_TOUCH = null;
134 // Suffix appended to provider key for storing vm number
135 public static final String VM_NUMBER_TAG = "#VMNumber";
136 // Suffix appended to provider key for storing forwarding settings
137 public static final String FWD_SETTINGS_TAG = "#FWDSettings";
138 // Suffix appended to forward settings key for storing length of settings array
139 public static final String FWD_SETTINGS_LENGTH_TAG = "#Length";
140 // Suffix appended to forward settings key for storing an individual setting
141 public static final String FWD_SETTING_TAG = "#Setting";
142 // Suffixes appended to forward setting key for storing an individual setting properties
143 public static final String FWD_SETTING_STATUS = "#Status";
144 public static final String FWD_SETTING_REASON = "#Reason";
145 public static final String FWD_SETTING_NUMBER = "#Number";
146 public static final String FWD_SETTING_TIME = "#Time";
147
148 // Key identifying the default vocie mail provider
149 public static final String DEFAULT_VM_PROVIDER_KEY = "";
150
151 /**
152 * String Extra put into ACTION_ADD_VOICEMAIL call to indicate which provider should be hidden
153 * in the list of providers presented to the user. This allows a provider which is being
154 * disabled (e.g. GV user logging out) to force the user to pick some other provider.
155 */
156 public static final String IGNORE_PROVIDER_EXTRA = "com.android.phone.ProviderToIgnore";
157
158 // string constants
159 private static final String NUM_PROJECTION[] = {CommonDataKinds.Phone.NUMBER};
160
161 // String keys for preference lookup
162 // TODO: Naming these "BUTTON_*" is confusing since they're not actually buttons(!)
Ihab Awad098f2d72014-05-19 17:34:52 -0700163 private static final String BUTTON_DEFAULT_CONNECTION_SERVICE = "button_connection_service";
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700164 private static final String BUTTON_VOICEMAIL_KEY = "button_voicemail_key";
165 private static final String BUTTON_VOICEMAIL_PROVIDER_KEY = "button_voicemail_provider_key";
166 private static final String BUTTON_VOICEMAIL_SETTING_KEY = "button_voicemail_setting_key";
167 // New preference key for voicemail notification vibration
168 /* package */ static final String BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY =
169 "button_voicemail_notification_vibrate_key";
170 // Old preference key for voicemail notification vibration. Used for migration to the new
171 // preference key only.
172 /* package */ static final String BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_WHEN_KEY =
173 "button_voicemail_notification_vibrate_when_key";
174 /* package */ static final String BUTTON_VOICEMAIL_NOTIFICATION_RINGTONE_KEY =
175 "button_voicemail_notification_ringtone_key";
176 private static final String BUTTON_FDN_KEY = "button_fdn_key";
177 private static final String BUTTON_RESPOND_VIA_SMS_KEY = "button_respond_via_sms_key";
178
179 private static final String BUTTON_RINGTONE_KEY = "button_ringtone_key";
180 private static final String BUTTON_VIBRATE_ON_RING = "button_vibrate_on_ring";
181 private static final String BUTTON_PLAY_DTMF_TONE = "button_play_dtmf_tone";
182 private static final String BUTTON_DTMF_KEY = "button_dtmf_settings";
183 private static final String BUTTON_RETRY_KEY = "button_auto_retry_key";
184 private static final String BUTTON_TTY_KEY = "button_tty_mode_key";
185 private static final String BUTTON_HAC_KEY = "button_hac_key";
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700186
187 private static final String BUTTON_GSM_UMTS_OPTIONS = "button_gsm_more_expand_key";
188 private static final String BUTTON_CDMA_OPTIONS = "button_cdma_more_expand_key";
189
190 private static final String VM_NUMBERS_SHARED_PREFERENCES_NAME = "vm_numbers";
191
192 private static final String BUTTON_SIP_CALL_OPTIONS =
193 "sip_call_options_key";
194 private static final String BUTTON_SIP_CALL_OPTIONS_WIFI_ONLY =
195 "sip_call_options_wifi_only_key";
196 private static final String SIP_SETTINGS_CATEGORY_KEY =
197 "sip_settings_category_key";
198
199 private Intent mContactListIntent;
200
201 /** Event for Async voicemail change call */
202 private static final int EVENT_VOICEMAIL_CHANGED = 500;
203 private static final int EVENT_FORWARDING_CHANGED = 501;
204 private static final int EVENT_FORWARDING_GET_COMPLETED = 502;
205
206 private static final int MSG_UPDATE_RINGTONE_SUMMARY = 1;
207 private static final int MSG_UPDATE_VOICEMAIL_RINGTONE_SUMMARY = 2;
208
209 // preferred TTY mode
210 // Phone.TTY_MODE_xxx
211 static final int preferredTtyMode = Phone.TTY_MODE_OFF;
212
213 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
810 // TODO(iliat): It would be nice to load the current network setting for this and
811 // 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 {
1561 prefSet.removePreference(mVibrateWhenRinging);
1562 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) {
1602 if (getResources().getBoolean(R.bool.tty_enabled)) {
1603 mButtonTTY.setOnPreferenceChangeListener(this);
1604 } else {
1605 prefSet.removePreference(mButtonTTY);
1606 mButtonTTY = null;
1607 }
1608 }
1609
1610 if (!getResources().getBoolean(R.bool.world_phone)) {
1611 Preference options = prefSet.findPreference(BUTTON_CDMA_OPTIONS);
1612 if (options != null)
1613 prefSet.removePreference(options);
1614 options = prefSet.findPreference(BUTTON_GSM_UMTS_OPTIONS);
1615 if (options != null)
1616 prefSet.removePreference(options);
1617
1618 int phoneType = mPhone.getPhoneType();
1619 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1620 Preference fdnButton = prefSet.findPreference(BUTTON_FDN_KEY);
1621 if (fdnButton != null)
1622 prefSet.removePreference(fdnButton);
1623 if (!getResources().getBoolean(R.bool.config_voice_privacy_disable)) {
1624 addPreferencesFromResource(R.xml.cdma_call_privacy);
1625 }
1626 } else if (phoneType == PhoneConstants.PHONE_TYPE_GSM) {
Etan Cohen0ca1c802014-07-07 15:35:48 -07001627 if (getResources().getBoolean(
1628 R.bool.config_additional_call_setting)) {
1629 addPreferencesFromResource(R.xml.gsm_umts_call_options);
1630 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001631 } else {
1632 throw new IllegalStateException("Unexpected phone type: " + phoneType);
1633 }
1634 }
1635
1636 // create intent to bring up contact list
1637 mContactListIntent = new Intent(Intent.ACTION_GET_CONTENT);
1638 mContactListIntent.setType(android.provider.Contacts.Phones.CONTENT_ITEM_TYPE);
1639
1640 // check the intent that started this activity and pop up the voicemail
1641 // dialog if we've been asked to.
1642 // If we have at least one non default VM provider registered then bring up
1643 // the selection for the VM provider, otherwise bring up a VM number dialog.
1644 // We only bring up the dialog the first time we are called (not after orientation change)
1645 if (icicle == null) {
1646 if (getIntent().getAction().equals(ACTION_ADD_VOICEMAIL) &&
1647 mVoicemailProviders != null) {
1648 if (DBG) {
1649 log("ACTION_ADD_VOICEMAIL Intent is thrown. current VM data size: "
1650 + mVMProvidersData.size());
1651 }
1652 if (mVMProvidersData.size() > 1) {
1653 simulatePreferenceClick(mVoicemailProviders);
1654 } else {
1655 onPreferenceChange(mVoicemailProviders, DEFAULT_VM_PROVIDER_KEY);
1656 mVoicemailProviders.setValue(DEFAULT_VM_PROVIDER_KEY);
1657 }
1658 }
1659 }
1660 updateVoiceNumberField();
1661 mVMProviderSettingsForced = false;
1662 createSipCallSettings();
1663
1664 mRingtoneLookupRunnable = new Runnable() {
1665 @Override
1666 public void run() {
1667 if (mRingtonePreference != null) {
1668 updateRingtoneName(RingtoneManager.TYPE_RINGTONE, mRingtonePreference,
1669 MSG_UPDATE_RINGTONE_SUMMARY);
1670 }
1671 if (mVoicemailNotificationRingtone != null) {
1672 updateRingtoneName(RingtoneManager.TYPE_NOTIFICATION,
1673 mVoicemailNotificationRingtone, MSG_UPDATE_VOICEMAIL_RINGTONE_SUMMARY);
1674 }
1675 }
1676 };
1677
1678 ActionBar actionBar = getActionBar();
1679 if (actionBar != null) {
1680 // android.R.id.home will be triggered in onOptionsItemSelected()
Yorke Lee88bf3cc2013-09-10 18:45:12 -07001681 actionBar.setDisplayShowHomeEnabled(true);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001682 actionBar.setDisplayHomeAsUpEnabled(true);
Yorke Lee88bf3cc2013-09-10 18:45:12 -07001683 actionBar.setDisplayShowTitleEnabled(true);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001684 }
Ihab Awad098f2d72014-05-19 17:34:52 -07001685
1686 if (mConnectionService != null) {
1687 mConnectionService.setOnPreferenceChangeListener(this);
1688 setupConnectionServiceOptions();
1689 updateConnectionServiceSummary(null);
1690 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001691 }
1692
1693 /**
1694 * Updates ringtone name. This is a method copied from com.android.settings.SoundSettings
1695 *
1696 * @see com.android.settings.SoundSettings
1697 */
1698 private void updateRingtoneName(int type, Preference preference, int msg) {
1699 if (preference == null) return;
1700 final Uri ringtoneUri;
1701 boolean defaultRingtone = false;
1702 if (type == RingtoneManager.TYPE_RINGTONE) {
1703 // For ringtones, we can just lookup the system default because changing the settings
1704 // in Call Settings changes the system default.
1705 ringtoneUri = RingtoneManager.getActualDefaultRingtoneUri(this, type);
1706 } else {
1707 final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(
1708 mPhone.getContext());
1709 // for voicemail notifications, we use the value saved in Phone's shared preferences.
1710 String uriString = prefs.getString(preference.getKey(), null);
1711 if (TextUtils.isEmpty(uriString)) {
1712 // silent ringtone
1713 ringtoneUri = null;
1714 } else {
1715 if (uriString.equals(Settings.System.DEFAULT_NOTIFICATION_URI.toString())) {
1716 // If it turns out that the voicemail notification is set to the system
1717 // default notification, we retrieve the actual URI to prevent it from showing
1718 // up as "Unknown Ringtone".
1719 defaultRingtone = true;
1720 ringtoneUri = RingtoneManager.getActualDefaultRingtoneUri(this, type);
1721 } else {
1722 ringtoneUri = Uri.parse(uriString);
1723 }
1724 }
1725 }
1726 CharSequence summary = getString(com.android.internal.R.string.ringtone_unknown);
1727 // Is it a silent ringtone?
1728 if (ringtoneUri == null) {
1729 summary = getString(com.android.internal.R.string.ringtone_silent);
1730 } else {
1731 // Fetch the ringtone title from the media provider
1732 try {
1733 Cursor cursor = getContentResolver().query(ringtoneUri,
1734 new String[] { MediaStore.Audio.Media.TITLE }, null, null, null);
1735 if (cursor != null) {
1736 if (cursor.moveToFirst()) {
1737 summary = cursor.getString(0);
1738 }
1739 cursor.close();
1740 }
1741 } catch (SQLiteException sqle) {
1742 // Unknown title for the ringtone
1743 }
1744 }
1745 if (defaultRingtone) {
1746 summary = mPhone.getContext().getString(
1747 R.string.default_notification_description, summary);
1748 }
1749 mRingtoneLookupComplete.sendMessage(mRingtoneLookupComplete.obtainMessage(msg, summary));
1750 }
1751
1752 private void createSipCallSettings() {
1753 // Add Internet call settings.
1754 if (PhoneUtils.isVoipSupported()) {
1755 mSipManager = SipManager.newInstance(this);
1756 mSipSharedPreferences = new SipSharedPreferences(this);
1757 addPreferencesFromResource(R.xml.sip_settings_category);
1758 mButtonSipCallOptions = getSipCallOptionPreference();
1759 mButtonSipCallOptions.setOnPreferenceChangeListener(this);
1760 mButtonSipCallOptions.setValueIndex(
1761 mButtonSipCallOptions.findIndexOfValue(
1762 mSipSharedPreferences.getSipCallOption()));
1763 mButtonSipCallOptions.setSummary(mButtonSipCallOptions.getEntry());
1764 }
1765 }
1766
Evan Charlton1c696832014-04-15 14:24:23 -07001767 private boolean canLaunchIntent(Intent intent) {
1768 PackageManager pm = getPackageManager();
1769 return pm.resolveActivity(intent, PackageManager.GET_ACTIVITIES) != null;
Ihab Awadca8ee7d2013-12-05 12:13:16 -08001770 }
1771
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001772 // Gets the call options for SIP depending on whether SIP is allowed only
1773 // on Wi-Fi only; also make the other options preference invisible.
1774 private ListPreference getSipCallOptionPreference() {
1775 ListPreference wifiAnd3G = (ListPreference)
1776 findPreference(BUTTON_SIP_CALL_OPTIONS);
1777 ListPreference wifiOnly = (ListPreference)
1778 findPreference(BUTTON_SIP_CALL_OPTIONS_WIFI_ONLY);
1779 PreferenceGroup sipSettings = (PreferenceGroup)
1780 findPreference(SIP_SETTINGS_CATEGORY_KEY);
1781 if (SipManager.isSipWifiOnly(this)) {
1782 sipSettings.removePreference(wifiAnd3G);
1783 return wifiOnly;
1784 } else {
1785 sipSettings.removePreference(wifiOnly);
1786 return wifiAnd3G;
1787 }
1788 }
1789
1790 @Override
1791 protected void onResume() {
1792 super.onResume();
1793 mForeground = true;
1794
1795 if (isAirplaneModeOn()) {
1796 Preference sipSettings = findPreference(SIP_SETTINGS_CATEGORY_KEY);
1797 PreferenceScreen screen = getPreferenceScreen();
1798 int count = screen.getPreferenceCount();
1799 for (int i = 0 ; i < count ; ++i) {
1800 Preference pref = screen.getPreference(i);
1801 if (pref != sipSettings) pref.setEnabled(false);
1802 }
1803 return;
1804 }
1805
1806 if (mVibrateWhenRinging != null) {
1807 mVibrateWhenRinging.setChecked(getVibrateWhenRinging(this));
1808 }
1809
1810 if (mButtonDTMF != null) {
1811 int dtmf = Settings.System.getInt(getContentResolver(),
1812 Settings.System.DTMF_TONE_TYPE_WHEN_DIALING, Constants.DTMF_TONE_TYPE_NORMAL);
1813 mButtonDTMF.setValueIndex(dtmf);
1814 }
1815
1816 if (mButtonAutoRetry != null) {
1817 int autoretry = Settings.Global.getInt(getContentResolver(),
1818 Settings.Global.CALL_AUTO_RETRY, 0);
1819 mButtonAutoRetry.setChecked(autoretry != 0);
1820 }
1821
1822 if (mButtonHAC != null) {
1823 int hac = Settings.System.getInt(getContentResolver(), Settings.System.HEARING_AID, 0);
1824 mButtonHAC.setChecked(hac != 0);
1825 }
1826
1827 if (mButtonTTY != null) {
1828 int settingsTtyMode = Settings.Secure.getInt(getContentResolver(),
1829 Settings.Secure.PREFERRED_TTY_MODE,
1830 Phone.TTY_MODE_OFF);
1831 mButtonTTY.setValue(Integer.toString(settingsTtyMode));
1832 updatePreferredTtyModeSummary(settingsTtyMode);
1833 }
1834
1835 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(
1836 mPhone.getContext());
1837 if (migrateVoicemailVibrationSettingsIfNeeded(prefs)) {
1838 mVoicemailNotificationVibrate.setChecked(prefs.getBoolean(
1839 BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY, false));
1840 }
1841
1842 lookupRingtoneName();
1843 }
1844
1845 // Migrate settings from BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_WHEN_KEY to
1846 // BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY, if the latter does not exist.
1847 // Returns true if migration was performed.
1848 public static boolean migrateVoicemailVibrationSettingsIfNeeded(SharedPreferences prefs) {
1849 if (!prefs.contains(BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY)) {
1850 String vibrateWhen = prefs.getString(
1851 BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_WHEN_KEY, VOICEMAIL_VIBRATION_NEVER);
1852 // If vibrateWhen is always, then voicemailVibrate should be True.
1853 // otherwise if vibrateWhen is "only in silent mode", or "never", then
1854 // voicemailVibrate = False.
1855 boolean voicemailVibrate = vibrateWhen.equals(VOICEMAIL_VIBRATION_ALWAYS);
1856 final SharedPreferences.Editor editor = prefs.edit();
1857 editor.putBoolean(BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_KEY, voicemailVibrate);
1858 editor.commit();
1859 return true;
1860 }
1861 return false;
1862 }
1863
1864 /**
1865 * Obtain the setting for "vibrate when ringing" setting.
1866 *
1867 * Watch out: if the setting is missing in the device, this will try obtaining the old
1868 * "vibrate on ring" setting from AudioManager, and save the previous setting to the new one.
1869 */
1870 public static boolean getVibrateWhenRinging(Context context) {
1871 Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
1872 if (vibrator == null || !vibrator.hasVibrator()) {
1873 return false;
1874 }
1875 return Settings.System.getInt(context.getContentResolver(),
1876 Settings.System.VIBRATE_WHEN_RINGING, 0) != 0;
1877 }
1878
1879 /**
1880 * Lookups ringtone name asynchronously and updates the relevant Preference.
1881 */
1882 private void lookupRingtoneName() {
1883 new Thread(mRingtoneLookupRunnable).start();
1884 }
1885
1886 private boolean isAirplaneModeOn() {
1887 return Settings.System.getInt(getContentResolver(),
1888 Settings.System.AIRPLANE_MODE_ON, 0) != 0;
1889 }
1890
1891 private void handleTTYChange(Preference preference, Object objValue) {
1892 int buttonTtyMode;
1893 buttonTtyMode = Integer.valueOf((String) objValue).intValue();
1894 int settingsTtyMode = android.provider.Settings.Secure.getInt(
1895 getContentResolver(),
1896 android.provider.Settings.Secure.PREFERRED_TTY_MODE, preferredTtyMode);
1897 if (DBG) log("handleTTYChange: requesting set TTY mode enable (TTY) to" +
1898 Integer.toString(buttonTtyMode));
1899
1900 if (buttonTtyMode != settingsTtyMode) {
1901 switch(buttonTtyMode) {
1902 case Phone.TTY_MODE_OFF:
1903 case Phone.TTY_MODE_FULL:
1904 case Phone.TTY_MODE_HCO:
1905 case Phone.TTY_MODE_VCO:
1906 android.provider.Settings.Secure.putInt(getContentResolver(),
1907 android.provider.Settings.Secure.PREFERRED_TTY_MODE, buttonTtyMode);
1908 break;
1909 default:
1910 buttonTtyMode = Phone.TTY_MODE_OFF;
1911 }
1912
1913 mButtonTTY.setValue(Integer.toString(buttonTtyMode));
1914 updatePreferredTtyModeSummary(buttonTtyMode);
1915 Intent ttyModeChanged = new Intent(TtyIntent.TTY_PREFERRED_MODE_CHANGE_ACTION);
1916 ttyModeChanged.putExtra(TtyIntent.TTY_PREFFERED_MODE, buttonTtyMode);
1917 sendBroadcastAsUser(ttyModeChanged, UserHandle.ALL);
1918 }
1919 }
1920
1921 private void handleSipCallOptionsChange(Object objValue) {
1922 String option = objValue.toString();
1923 mSipSharedPreferences.setSipCallOption(option);
1924 mButtonSipCallOptions.setValueIndex(
1925 mButtonSipCallOptions.findIndexOfValue(option));
1926 mButtonSipCallOptions.setSummary(mButtonSipCallOptions.getEntry());
1927 }
1928
Evan Charlton1c696832014-04-15 14:24:23 -07001929 private void handleWifiCallSettingsClick(Preference preference) {
1930 Intent intent = preference.getIntent();
1931 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
1932 // TODO - Restrict to a (the?) blessed Wi-Fi calling app.
1933
1934 Bundle noAnimations = ActivityOptions.makeCustomAnimation(this, 0, 0).toBundle();
1935 startActivity(intent, noAnimations);
Ihab Awadca8ee7d2013-12-05 12:13:16 -08001936 }
1937
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001938 private void updatePreferredTtyModeSummary(int TtyMode) {
1939 String [] txts = getResources().getStringArray(R.array.tty_mode_entries);
1940 switch(TtyMode) {
1941 case Phone.TTY_MODE_OFF:
1942 case Phone.TTY_MODE_HCO:
1943 case Phone.TTY_MODE_VCO:
1944 case Phone.TTY_MODE_FULL:
1945 mButtonTTY.setSummary(txts[TtyMode]);
1946 break;
1947 default:
1948 mButtonTTY.setEnabled(false);
1949 mButtonTTY.setSummary(txts[Phone.TTY_MODE_OFF]);
1950 }
1951 }
1952
1953 private static void log(String msg) {
1954 Log.d(LOG_TAG, msg);
1955 }
1956
1957 /**
1958 * Updates the look of the VM preference widgets based on current VM provider settings.
1959 * Note that the provider name is loaded form the found activity via loadLabel in
1960 * {@link #initVoiceMailProviders()} in order for it to be localizable.
1961 */
1962 private void updateVMPreferenceWidgets(String currentProviderSetting) {
1963 final String key = currentProviderSetting;
1964 final VoiceMailProvider provider = mVMProvidersData.get(key);
1965
1966 /* This is the case when we are coming up on a freshly wiped phone and there is no
1967 persisted value for the list preference mVoicemailProviders.
1968 In this case we want to show the UI asking the user to select a voicemail provider as
1969 opposed to silently falling back to default one. */
1970 if (provider == null) {
1971 if (DBG) {
1972 log("updateVMPreferenceWidget: provider for the key \"" + key + "\" is null.");
1973 }
1974 mVoicemailProviders.setSummary(getString(R.string.sum_voicemail_choose_provider));
1975 mVoicemailSettings.setEnabled(false);
1976 mVoicemailSettings.setIntent(null);
1977
1978 mVoicemailNotificationVibrate.setEnabled(false);
1979 } else {
1980 if (DBG) {
1981 log("updateVMPreferenceWidget: provider for the key \"" + key + "\".."
1982 + "name: " + provider.name
1983 + ", intent: " + provider.intent);
1984 }
1985 final String providerName = provider.name;
1986 mVoicemailProviders.setSummary(providerName);
1987 mVoicemailSettings.setEnabled(true);
1988 mVoicemailSettings.setIntent(provider.intent);
1989
1990 mVoicemailNotificationVibrate.setEnabled(true);
1991 }
1992 }
1993
1994 /**
1995 * Enumerates existing VM providers and puts their data into the list and populates
1996 * the preference list objects with their names.
1997 * In case we are called with ACTION_ADD_VOICEMAIL intent the intent may have
1998 * an extra string called IGNORE_PROVIDER_EXTRA with "package.activityName" of the provider
1999 * which should be hidden when we bring up the list of possible VM providers to choose.
2000 */
2001 private void initVoiceMailProviders() {
2002 if (DBG) log("initVoiceMailProviders()");
2003 mPerProviderSavedVMNumbers =
2004 this.getApplicationContext().getSharedPreferences(
2005 VM_NUMBERS_SHARED_PREFERENCES_NAME, MODE_PRIVATE);
2006
2007 String providerToIgnore = null;
2008 if (getIntent().getAction().equals(ACTION_ADD_VOICEMAIL)) {
2009 if (getIntent().hasExtra(IGNORE_PROVIDER_EXTRA)) {
2010 providerToIgnore = getIntent().getStringExtra(IGNORE_PROVIDER_EXTRA);
2011 }
2012 if (DBG) log("Found ACTION_ADD_VOICEMAIL. providerToIgnore=" + providerToIgnore);
2013 if (providerToIgnore != null) {
2014 // IGNORE_PROVIDER_EXTRA implies we want to remove the choice from the list.
2015 deleteSettingsForVoicemailProvider(providerToIgnore);
2016 }
2017 }
2018
2019 mVMProvidersData.clear();
2020
2021 // Stick the default element which is always there
2022 final String myCarrier = getString(R.string.voicemail_default);
2023 mVMProvidersData.put(DEFAULT_VM_PROVIDER_KEY, new VoiceMailProvider(myCarrier, null));
2024
2025 // Enumerate providers
2026 PackageManager pm = getPackageManager();
2027 Intent intent = new Intent();
2028 intent.setAction(ACTION_CONFIGURE_VOICEMAIL);
2029 List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
2030 int len = resolveInfos.size() + 1; // +1 for the default choice we will insert.
2031
2032 // Go through the list of discovered providers populating the data map
2033 // skip the provider we were instructed to ignore if there was one
2034 for (int i = 0; i < resolveInfos.size(); i++) {
2035 final ResolveInfo ri= resolveInfos.get(i);
2036 final ActivityInfo currentActivityInfo = ri.activityInfo;
2037 final String key = makeKeyForActivity(currentActivityInfo);
2038 if (key.equals(providerToIgnore)) {
2039 if (DBG) log("Ignoring key: " + key);
2040 len--;
2041 continue;
2042 }
2043 if (DBG) log("Loading key: " + key);
2044 final String nameForDisplay = ri.loadLabel(pm).toString();
2045 Intent providerIntent = new Intent();
2046 providerIntent.setAction(ACTION_CONFIGURE_VOICEMAIL);
2047 providerIntent.setClassName(currentActivityInfo.packageName,
2048 currentActivityInfo.name);
2049 if (DBG) {
2050 log("Store loaded VoiceMailProvider. key: " + key
2051 + " -> name: " + nameForDisplay + ", intent: " + providerIntent);
2052 }
2053 mVMProvidersData.put(
2054 key,
2055 new VoiceMailProvider(nameForDisplay, providerIntent));
2056
2057 }
2058
2059 // Now we know which providers to display - create entries and values array for
2060 // the list preference
2061 String [] entries = new String [len];
2062 String [] values = new String [len];
2063 entries[0] = myCarrier;
2064 values[0] = DEFAULT_VM_PROVIDER_KEY;
2065 int entryIdx = 1;
2066 for (int i = 0; i < resolveInfos.size(); i++) {
2067 final String key = makeKeyForActivity(resolveInfos.get(i).activityInfo);
2068 if (!mVMProvidersData.containsKey(key)) {
2069 continue;
2070 }
2071 entries[entryIdx] = mVMProvidersData.get(key).name;
2072 values[entryIdx] = key;
2073 entryIdx++;
2074 }
2075
2076 // ListPreference is now updated.
2077 mVoicemailProviders.setEntries(entries);
2078 mVoicemailProviders.setEntryValues(values);
2079
2080 // Remember the current Voicemail Provider key as a "previous" key. This will be used
2081 // when we fail to update Voicemail Provider, which requires rollback.
2082 // We will update this when the VM Provider setting is successfully updated.
2083 mPreviousVMProviderKey = getCurrentVoicemailProviderKey();
2084 if (DBG) log("Set up the first mPreviousVMProviderKey: " + mPreviousVMProviderKey);
2085
2086 // Finally update the preference texts.
2087 updateVMPreferenceWidgets(mPreviousVMProviderKey);
2088 }
2089
2090 private String makeKeyForActivity(ActivityInfo ai) {
2091 return ai.name;
2092 }
2093
2094 /**
2095 * Simulates user clicking on a passed preference.
2096 * Usually needed when the preference is a dialog preference and we want to invoke
2097 * a dialog for this preference programmatically.
2098 * TODO(iliat): figure out if there is a cleaner way to cause preference dlg to come up
2099 */
2100 private void simulatePreferenceClick(Preference preference) {
2101 // Go through settings until we find our setting
2102 // and then simulate a click on it to bring up the dialog
2103 final ListAdapter adapter = getPreferenceScreen().getRootAdapter();
2104 for (int idx = 0; idx < adapter.getCount(); idx++) {
2105 if (adapter.getItem(idx) == preference) {
2106 getPreferenceScreen().onItemClick(this.getListView(),
2107 null, idx, adapter.getItemId(idx));
2108 break;
2109 }
2110 }
2111 }
2112
2113 /**
2114 * Saves new VM provider settings associating them with the currently selected
2115 * provider if settings are different than the ones already stored for this
2116 * provider.
2117 * Later on these will be used when the user switches a provider.
2118 */
2119 private void maybeSaveSettingsForVoicemailProvider(String key,
2120 VoiceMailProviderSettings newSettings) {
2121 if (mVoicemailProviders == null) {
2122 return;
2123 }
2124 final VoiceMailProviderSettings curSettings = loadSettingsForVoiceMailProvider(key);
2125 if (newSettings.equals(curSettings)) {
2126 if (DBG) {
2127 log("maybeSaveSettingsForVoicemailProvider:"
2128 + " Not saving setting for " + key + " since they have not changed");
2129 }
2130 return;
2131 }
2132 if (DBG) log("Saving settings for " + key + ": " + newSettings.toString());
2133 Editor editor = mPerProviderSavedVMNumbers.edit();
2134 editor.putString(key + VM_NUMBER_TAG, newSettings.voicemailNumber);
2135 String fwdKey = key + FWD_SETTINGS_TAG;
2136 CallForwardInfo[] s = newSettings.forwardingSettings;
2137 if (s != FWD_SETTINGS_DONT_TOUCH) {
2138 editor.putInt(fwdKey + FWD_SETTINGS_LENGTH_TAG, s.length);
2139 for (int i = 0; i < s.length; i++) {
2140 final String settingKey = fwdKey + FWD_SETTING_TAG + String.valueOf(i);
2141 final CallForwardInfo fi = s[i];
2142 editor.putInt(settingKey + FWD_SETTING_STATUS, fi.status);
2143 editor.putInt(settingKey + FWD_SETTING_REASON, fi.reason);
2144 editor.putString(settingKey + FWD_SETTING_NUMBER, fi.number);
2145 editor.putInt(settingKey + FWD_SETTING_TIME, fi.timeSeconds);
2146 }
2147 } else {
2148 editor.putInt(fwdKey + FWD_SETTINGS_LENGTH_TAG, 0);
2149 }
2150 editor.apply();
2151 }
2152
2153 /**
2154 * Returns settings previously stored for the currently selected
2155 * voice mail provider. If none is stored returns null.
2156 * If the user switches to a voice mail provider and we have settings
2157 * stored for it we will automatically change the phone's voice mail number
2158 * and forwarding number to the stored one. Otherwise we will bring up provider's configuration
2159 * UI.
2160 */
2161 private VoiceMailProviderSettings loadSettingsForVoiceMailProvider(String key) {
2162 final String vmNumberSetting = mPerProviderSavedVMNumbers.getString(key + VM_NUMBER_TAG,
2163 null);
2164 if (vmNumberSetting == null) {
2165 Log.w(LOG_TAG, "VoiceMailProvider settings for the key \"" + key + "\""
2166 + " was not found. Returning null.");
2167 return null;
2168 }
2169
2170 CallForwardInfo[] cfi = FWD_SETTINGS_DONT_TOUCH;
2171 String fwdKey = key + FWD_SETTINGS_TAG;
2172 final int fwdLen = mPerProviderSavedVMNumbers.getInt(fwdKey + FWD_SETTINGS_LENGTH_TAG, 0);
2173 if (fwdLen > 0) {
2174 cfi = new CallForwardInfo[fwdLen];
2175 for (int i = 0; i < cfi.length; i++) {
2176 final String settingKey = fwdKey + FWD_SETTING_TAG + String.valueOf(i);
2177 cfi[i] = new CallForwardInfo();
2178 cfi[i].status = mPerProviderSavedVMNumbers.getInt(
2179 settingKey + FWD_SETTING_STATUS, 0);
2180 cfi[i].reason = mPerProviderSavedVMNumbers.getInt(
2181 settingKey + FWD_SETTING_REASON,
2182 CommandsInterface.CF_REASON_ALL_CONDITIONAL);
2183 cfi[i].serviceClass = CommandsInterface.SERVICE_CLASS_VOICE;
2184 cfi[i].toa = PhoneNumberUtils.TOA_International;
2185 cfi[i].number = mPerProviderSavedVMNumbers.getString(
2186 settingKey + FWD_SETTING_NUMBER, "");
2187 cfi[i].timeSeconds = mPerProviderSavedVMNumbers.getInt(
2188 settingKey + FWD_SETTING_TIME, 20);
2189 }
2190 }
2191
2192 VoiceMailProviderSettings settings = new VoiceMailProviderSettings(vmNumberSetting, cfi);
2193 if (DBG) log("Loaded settings for " + key + ": " + settings.toString());
2194 return settings;
2195 }
2196
2197 /**
2198 * Deletes settings for the specified provider.
2199 */
2200 private void deleteSettingsForVoicemailProvider(String key) {
2201 if (DBG) log("Deleting settings for" + key);
2202 if (mVoicemailProviders == null) {
2203 return;
2204 }
2205 mPerProviderSavedVMNumbers.edit()
2206 .putString(key + VM_NUMBER_TAG, null)
2207 .putInt(key + FWD_SETTINGS_TAG + FWD_SETTINGS_LENGTH_TAG, 0)
2208 .commit();
2209 }
2210
2211 private String getCurrentVoicemailProviderKey() {
2212 final String key = mVoicemailProviders.getValue();
2213 return (key != null) ? key : DEFAULT_VM_PROVIDER_KEY;
2214 }
2215
2216 @Override
2217 public boolean onOptionsItemSelected(MenuItem item) {
2218 final int itemId = item.getItemId();
2219 if (itemId == android.R.id.home) { // See ActionBar#setDisplayHomeAsUpEnabled()
Yorke Leef2d0cac2013-09-09 19:42:56 -07002220 onBackPressed();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002221 return true;
2222 }
2223 return super.onOptionsItemSelected(item);
2224 }
2225
Ihab Awad098f2d72014-05-19 17:34:52 -07002226 private void setupConnectionServiceOptions() {
2227 loadConnectionServiceEntries();
2228 String[] entryValues = new String[mConnectionServiceLabelByComponentName.size()];
2229 CharSequence[] entries = new CharSequence[mConnectionServiceLabelByComponentName.size()];
2230 int i = 0;
2231 for (String entryValue : mConnectionServiceLabelByComponentName.keySet()) {
2232 entryValues[i] = entryValue;
2233 entries[i] = mConnectionServiceLabelByComponentName.get(entryValue);
2234 i++;
2235 }
2236 mConnectionService.setEntryValues(entryValues);
2237 mConnectionService.setEntries(entries);
2238
2239 if (mConnectionService.getValue() == null) {
2240 mConnectionService.setValue(getString(R.string.connection_service_default));
2241 }
2242 }
2243
2244 private void updateConnectionServiceSummary(String value) {
2245 CharSequence label = mConnectionServiceLabelByComponentName.get(
2246 value == null ? mConnectionService.getValue() : value);
2247 if (label == null) {
2248 Log.wtf(LOG_TAG, "Unknown default connection service entry " +
2249 mConnectionService.getValue());
2250 mConnectionService.setSummary("");
2251 }
2252 mConnectionService.setSummary(label);
2253 }
2254
2255 private void loadConnectionServiceEntries() {
Sailesh Nepal536cff02014-07-04 19:44:01 -07002256 Intent intent = new Intent(TelecommConstants.ACTION_CONNECTION_SERVICE);
Ihab Awad098f2d72014-05-19 17:34:52 -07002257 for (ResolveInfo entry : getPackageManager().queryIntentServices(intent, 0)) {
2258 ServiceInfo serviceInfo = entry.serviceInfo;
2259 if (serviceInfo != null) {
2260 // The entry resolves to a proper service, add it to the list of service names
2261 ComponentName componentName =
2262 new ComponentName(serviceInfo.packageName, serviceInfo.name);
2263 mConnectionServiceLabelByComponentName.put(
2264 componentName.flattenToString(),
2265 serviceInfo.loadLabel(getPackageManager()));
2266 }
2267 }
2268
2269 // If the default built-in ConnectionService is not installed, according to the package
2270 // manager, then in a newly initialized system, Telecomm is going to read the preference
2271 // and find the service to be nonexistent. Telecomm should have error checking for this
2272 // case, but it is problematic and it's hard to program around it. Here we simply pretend
2273 // like the built-in default is installed anyway (so the default value defined in the XML
2274 // for the ListPreference points to something useful and does not throw an NPE) and proceed.
2275 String connectionServiceDefault = getString(R.string.connection_service_default);
2276 if (!mConnectionServiceLabelByComponentName.containsKey(connectionServiceDefault)) {
Ihab Awad38735432014-07-07 10:02:15 -07002277 Log.w(LOG_TAG, "Package manager reports built-in ConnectionService not installed: "
Ihab Awad098f2d72014-05-19 17:34:52 -07002278 + connectionServiceDefault);
Ihab Awad38735432014-07-07 10:02:15 -07002279 } else {
Ihab Awad098f2d72014-05-19 17:34:52 -07002280 mConnectionServiceLabelByComponentName.put(
2281 connectionServiceDefault,
2282 getString(R.string.connection_service_default_label));
2283 }
2284 }
2285
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002286 /**
2287 * Finish current Activity and go up to the top level Settings ({@link CallFeaturesSetting}).
2288 * This is useful for implementing "HomeAsUp" capability for second-level Settings.
2289 */
2290 public static void goUpToTopLevelSetting(Activity activity) {
2291 Intent intent = new Intent(activity, CallFeaturesSetting.class);
2292 intent.setAction(Intent.ACTION_MAIN);
2293 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
2294 activity.startActivity(intent);
2295 activity.finish();
2296 }
2297}