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