DevelopmentSettings.java revision 80d580731dfe6757d7a7a2f7e052daa552616254
1/*
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.settings.development;
18
19import android.Manifest;
20import android.app.Activity;
21import android.app.ActivityManager;
22import android.app.AlertDialog;
23import android.app.AppOpsManager;
24import android.app.AppOpsManager.PackageOps;
25import android.app.Dialog;
26import android.app.backup.IBackupManager;
27import android.bluetooth.BluetoothA2dp;
28import android.bluetooth.BluetoothAdapter;
29import android.bluetooth.BluetoothCodecConfig;
30import android.bluetooth.BluetoothCodecStatus;
31import android.bluetooth.BluetoothHeadset;
32import android.bluetooth.BluetoothProfile;
33import android.content.BroadcastReceiver;
34import android.content.ContentResolver;
35import android.content.Context;
36import android.content.DialogInterface;
37import android.content.Intent;
38import android.content.IntentFilter;
39import android.content.pm.ApplicationInfo;
40import android.content.pm.IShortcutService;
41import android.content.pm.PackageManager;
42import android.content.pm.PackageManager.NameNotFoundException;
43import android.content.pm.ResolveInfo;
44import android.content.res.Resources;
45import android.hardware.usb.IUsbManager;
46import android.hardware.usb.UsbManager;
47import android.net.wifi.WifiManager;
48import android.os.AsyncTask;
49import android.os.BatteryManager;
50import android.os.Build;
51import android.os.Bundle;
52import android.os.IBinder;
53import android.os.Parcel;
54import android.os.RemoteException;
55import android.os.ServiceManager;
56import android.os.StrictMode;
57import android.os.SystemProperties;
58import android.os.UserManager;
59import android.os.storage.IStorageManager;
60import android.provider.SearchIndexableResource;
61import android.provider.Settings;
62import android.service.oemlock.OemLockManager;
63import android.support.annotation.VisibleForTesting;
64import android.support.v14.preference.SwitchPreference;
65import android.support.v7.preference.ListPreference;
66import android.support.v7.preference.Preference;
67import android.support.v7.preference.Preference.OnPreferenceChangeListener;
68import android.support.v7.preference.PreferenceGroup;
69import android.support.v7.preference.PreferenceScreen;
70import android.telephony.TelephonyManager;
71import android.text.TextUtils;
72import android.util.Log;
73import android.view.IWindowManager;
74import android.view.LayoutInflater;
75import android.view.ThreadedRenderer;
76import android.view.View;
77import android.view.ViewGroup;
78import android.view.accessibility.AccessibilityManager;
79import android.webkit.IWebViewUpdateService;
80import android.webkit.WebViewFactory;
81import android.widget.Switch;
82import android.widget.Toast;
83
84import com.android.internal.app.LocalePicker;
85import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
86import com.android.settings.ChooseLockSettingsHelper;
87import com.android.settings.R;
88import com.android.settings.RestrictedSettingsFragment;
89import com.android.settings.SettingsActivity;
90import com.android.settings.Utils;
91import com.android.settings.dashboard.DashboardFeatureProvider;
92import com.android.settings.overlay.FeatureFactory;
93import com.android.settings.search.BaseSearchIndexProvider;
94import com.android.settings.search.Indexable;
95import com.android.settings.webview.WebViewAppPreferenceController;
96import com.android.settings.widget.SwitchBar;
97import com.android.settingslib.RestrictedLockUtils;
98import com.android.settingslib.RestrictedLockUtils.EnforcedAdmin;
99import com.android.settingslib.RestrictedSwitchPreference;
100import com.android.settingslib.drawer.CategoryKey;
101
102import java.util.ArrayList;
103import java.util.Arrays;
104import java.util.HashSet;
105import java.util.List;
106
107/*
108 * Displays preferences for application developers.
109 */
110public class DevelopmentSettings extends RestrictedSettingsFragment
111        implements DialogInterface.OnClickListener, DialogInterface.OnDismissListener,
112        OnPreferenceChangeListener, SwitchBar.OnSwitchChangeListener, Indexable {
113    private static final String TAG = "DevelopmentSettings";
114
115    /**
116     * Preference file were development settings prefs are stored.
117     */
118    public static final String PREF_FILE = "development";
119
120    /**
121     * Whether to show the development settings to the user.  Default is false.
122     */
123    public static final String PREF_SHOW = "show";
124
125    private static final String ENABLE_ADB = "enable_adb";
126    private static final String CLEAR_ADB_KEYS = "clear_adb_keys";
127    private static final String ENABLE_TERMINAL = "enable_terminal";
128    private static final String KEEP_SCREEN_ON = "keep_screen_on";
129    private static final String BT_HCI_SNOOP_LOG = "bt_hci_snoop_log";
130    private static final String ENABLE_OEM_UNLOCK = "oem_unlock_enable";
131    private static final String HDCP_CHECKING_KEY = "hdcp_checking";
132    private static final String HDCP_CHECKING_PROPERTY = "persist.sys.hdcp_checking";
133    private static final String LOCAL_BACKUP_PASSWORD = "local_backup_password";
134    private static final String HARDWARE_UI_PROPERTY = "persist.sys.ui.hw";
135    private static final String MSAA_PROPERTY = "debug.egl.force_msaa";
136    private static final String OPENGL_TRACES_PROPERTY = "debug.egl.trace";
137    private static final String TUNER_UI_KEY = "tuner_ui";
138    private static final String COLOR_TEMPERATURE_PROPERTY = "persist.sys.debug.color_temp";
139
140    private static final String DEBUG_APP_KEY = "debug_app";
141    private static final String WAIT_FOR_DEBUGGER_KEY = "wait_for_debugger";
142    private static final String MOCK_LOCATION_APP_KEY = "mock_location_app";
143    private static final String VERIFY_APPS_OVER_USB_KEY = "verify_apps_over_usb";
144    private static final String DEBUG_VIEW_ATTRIBUTES = "debug_view_attributes";
145    private static final String FORCE_ALLOW_ON_EXTERNAL_KEY = "force_allow_on_external";
146    private static final String STRICT_MODE_KEY = "strict_mode";
147    private static final String POINTER_LOCATION_KEY = "pointer_location";
148    private static final String SHOW_TOUCHES_KEY = "show_touches";
149    private static final String SHOW_SCREEN_UPDATES_KEY = "show_screen_updates";
150    private static final String DISABLE_OVERLAYS_KEY = "disable_overlays";
151    private static final String SIMULATE_COLOR_SPACE = "simulate_color_space";
152    private static final String USB_AUDIO_KEY = "usb_audio";
153    private static final String FORCE_HARDWARE_UI_KEY = "force_hw_ui";
154    private static final String FORCE_MSAA_KEY = "force_msaa";
155    private static final String TRACK_FRAME_TIME_KEY = "track_frame_time";
156    private static final String SHOW_NON_RECTANGULAR_CLIP_KEY = "show_non_rect_clip";
157    private static final String SHOW_HW_SCREEN_UPDATES_KEY = "show_hw_screen_udpates";
158    private static final String SHOW_HW_LAYERS_UPDATES_KEY = "show_hw_layers_udpates";
159    private static final String DEBUG_HW_OVERDRAW_KEY = "debug_hw_overdraw";
160    private static final String DEBUG_HW_RENDERER_KEY = "debug_hw_renderer";
161    private static final String DEBUG_LAYOUT_KEY = "debug_layout";
162    private static final String FORCE_RTL_LAYOUT_KEY = "force_rtl_layout_all_locales";
163    private static final String WINDOW_ANIMATION_SCALE_KEY = "window_animation_scale";
164    private static final String TRANSITION_ANIMATION_SCALE_KEY = "transition_animation_scale";
165    private static final String ANIMATOR_DURATION_SCALE_KEY = "animator_duration_scale";
166    private static final String OVERLAY_DISPLAY_DEVICES_KEY = "overlay_display_devices";
167    private static final String DEBUG_DEBUGGING_CATEGORY_KEY = "debug_debugging_category";
168    private static final String SELECT_LOGD_SIZE_KEY = "select_logd_size";
169    private static final String SELECT_LOGD_SIZE_PROPERTY = "persist.logd.size";
170    private static final String SELECT_LOGD_TAG_PROPERTY = "persist.log.tag";
171    // Tricky, isLoggable only checks for first character, assumes silence
172    private static final String SELECT_LOGD_TAG_SILENCE = "Settings";
173    private static final String SELECT_LOGD_SNET_TAG_PROPERTY = "persist.log.tag.snet_event_log";
174    private static final String SELECT_LOGD_RUNTIME_SNET_TAG_PROPERTY = "log.tag.snet_event_log";
175    private static final String SELECT_LOGD_DEFAULT_SIZE_PROPERTY = "ro.logd.size";
176    private static final String SELECT_LOGD_DEFAULT_SIZE_VALUE = "262144";
177    private static final String SELECT_LOGD_SVELTE_DEFAULT_SIZE_VALUE = "65536";
178    // 32768 is merely a menu marker, 64K is our lowest log buffer size we replace it with.
179    private static final String SELECT_LOGD_MINIMUM_SIZE_VALUE = "65536";
180    private static final String SELECT_LOGD_OFF_SIZE_MARKER_VALUE = "32768";
181    private static final String SELECT_LOGPERSIST_KEY = "select_logpersist";
182    private static final String SELECT_LOGPERSIST_PROPERTY = "persist.logd.logpersistd";
183    private static final String ACTUAL_LOGPERSIST_PROPERTY = "logd.logpersistd";
184    private static final String SELECT_LOGPERSIST_PROPERTY_SERVICE = "logcatd";
185    private static final String SELECT_LOGPERSIST_PROPERTY_CLEAR = "clear";
186    private static final String SELECT_LOGPERSIST_PROPERTY_STOP = "stop";
187    private static final String SELECT_LOGPERSIST_PROPERTY_BUFFER =
188            "persist.logd.logpersistd.buffer";
189    private static final String ACTUAL_LOGPERSIST_PROPERTY_BUFFER = "logd.logpersistd.buffer";
190    private static final String ACTUAL_LOGPERSIST_PROPERTY_ENABLE = "logd.logpersistd.enable";
191
192    private static final String WIFI_DISPLAY_CERTIFICATION_KEY = "wifi_display_certification";
193    private static final String WIFI_VERBOSE_LOGGING_KEY = "wifi_verbose_logging";
194    private static final String WIFI_AGGRESSIVE_HANDOVER_KEY = "wifi_aggressive_handover";
195    private static final String WIFI_ALLOW_SCAN_WITH_TRAFFIC_KEY = "wifi_allow_scan_with_traffic";
196    private static final String USB_CONFIGURATION_KEY = "select_usb_configuration";
197    private static final String MOBILE_DATA_ALWAYS_ON = "mobile_data_always_on";
198    private static final String KEY_COLOR_MODE = "color_mode";
199    private static final String FORCE_RESIZABLE_KEY = "force_resizable_activities";
200    private static final String COLOR_TEMPERATURE_KEY = "color_temperature";
201
202    private static final String BLUETOOTH_DISABLE_ABSOLUTE_VOLUME_KEY =
203            "bluetooth_disable_absolute_volume";
204    private static final String BLUETOOTH_DISABLE_ABSOLUTE_VOLUME_PROPERTY =
205            "persist.bluetooth.disableabsvol";
206    private static final String BLUETOOTH_AVRCP_VERSION_PROPERTY =
207                                    "persist.bluetooth.avrcpversion";
208    private static final String BLUETOOTH_ENABLE_INBAND_RINGING_PROPERTY =
209                                    "persist.bluetooth.enableinbandringing";
210    private static final String BLUETOOTH_BTSNOOP_ENABLE_PROPERTY =
211                                    "persist.bluetooth.btsnoopenable";
212
213    private static final String BLUETOOTH_ENABLE_INBAND_RINGING_KEY = "bluetooth_enable_inband_ringing";
214    private static final String BLUETOOTH_SELECT_AVRCP_VERSION_KEY = "bluetooth_select_avrcp_version";
215    private static final String BLUETOOTH_SELECT_A2DP_CODEC_KEY = "bluetooth_select_a2dp_codec";
216    private static final String BLUETOOTH_SELECT_A2DP_SAMPLE_RATE_KEY = "bluetooth_select_a2dp_sample_rate";
217    private static final String BLUETOOTH_SELECT_A2DP_BITS_PER_SAMPLE_KEY = "bluetooth_select_a2dp_bits_per_sample";
218    private static final String BLUETOOTH_SELECT_A2DP_CHANNEL_MODE_KEY = "bluetooth_select_a2dp_channel_mode";
219    private static final String BLUETOOTH_SELECT_A2DP_LDAC_PLAYBACK_QUALITY_KEY = "bluetooth_select_a2dp_ldac_playback_quality";
220
221    private static final String INACTIVE_APPS_KEY = "inactive_apps";
222
223    private static final String IMMEDIATELY_DESTROY_ACTIVITIES_KEY
224            = "immediately_destroy_activities";
225    private static final String APP_PROCESS_LIMIT_KEY = "app_process_limit";
226
227    private static final String BACKGROUND_CHECK_KEY = "background_check";
228
229    private static final String SHOW_ALL_ANRS_KEY = "show_all_anrs";
230
231    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
232
233    private static final String TERMINAL_APP_PACKAGE = "com.android.terminal";
234
235    private static final String KEY_CONVERT_FBE = "convert_to_file_encryption";
236
237    private static final String OTA_DISABLE_AUTOMATIC_UPDATE_KEY = "ota_disable_automatic_update";
238
239    private static final int RESULT_DEBUG_APP = 1000;
240    private static final int RESULT_MOCK_LOCATION_APP = 1001;
241
242    private static final String FLASH_LOCKED_PROP = "ro.boot.flash.locked";
243
244    private static final String SHORTCUT_MANAGER_RESET_KEY = "reset_shortcut_manager_throttling";
245
246    private static final int REQUEST_CODE_ENABLE_OEM_UNLOCK = 0;
247
248    private static final int[] MOCK_LOCATION_APP_OPS = new int[]{AppOpsManager.OP_MOCK_LOCATION};
249
250    private IWindowManager mWindowManager;
251    private IBackupManager mBackupManager;
252    private IWebViewUpdateService mWebViewUpdateService;
253    private UserManager mUm;
254    private WifiManager mWifiManager;
255    private OemLockManager mOemLockManager;
256    private TelephonyManager mTelephonyManager;
257
258    private SwitchBar mSwitchBar;
259
260    private boolean mHaveDebugSettings;
261    private boolean mDontPokeProperties;
262    private SwitchPreference mEnableAdb;
263    private Preference mClearAdbKeys;
264    private SwitchPreference mEnableTerminal;
265    private RestrictedSwitchPreference mKeepScreenOn;
266    private SwitchPreference mBtHciSnoopLog;
267    private RestrictedSwitchPreference mEnableOemUnlock;
268    private SwitchPreference mDebugViewAttributes;
269    private SwitchPreference mForceAllowOnExternal;
270
271    private Preference mPassword;
272    private String mDebugApp;
273    private Preference mDebugAppPref;
274
275    private String mMockLocationApp;
276    private Preference mMockLocationAppPref;
277
278    private SwitchPreference mWaitForDebugger;
279    private SwitchPreference mVerifyAppsOverUsb;
280    private SwitchPreference mWifiDisplayCertification;
281    private SwitchPreference mWifiVerboseLogging;
282    private SwitchPreference mWifiAggressiveHandover;
283    private SwitchPreference mMobileDataAlwaysOn;
284    private SwitchPreference mBluetoothDisableAbsVolume;
285    private SwitchPreference mBluetoothEnableInbandRinging;
286
287    private BluetoothA2dp mBluetoothA2dp;
288    private final Object mBluetoothA2dpLock = new Object();
289    private ListPreference mBluetoothSelectAvrcpVersion;
290    private ListPreference mBluetoothSelectA2dpCodec;
291    private ListPreference mBluetoothSelectA2dpSampleRate;
292    private ListPreference mBluetoothSelectA2dpBitsPerSample;
293    private ListPreference mBluetoothSelectA2dpChannelMode;
294    private ListPreference mBluetoothSelectA2dpLdacPlaybackQuality;
295
296    private SwitchPreference mOtaDisableAutomaticUpdate;
297    private SwitchPreference mWifiAllowScansWithTraffic;
298    private SwitchPreference mStrictMode;
299    private SwitchPreference mPointerLocation;
300    private SwitchPreference mShowTouches;
301    private SwitchPreference mShowScreenUpdates;
302    private SwitchPreference mDisableOverlays;
303    private SwitchPreference mForceHardwareUi;
304    private SwitchPreference mForceMsaa;
305    private SwitchPreference mShowHwScreenUpdates;
306    private SwitchPreference mShowHwLayersUpdates;
307    private SwitchPreference mDebugLayout;
308    private SwitchPreference mForceRtlLayout;
309    private ListPreference mDebugHwOverdraw;
310    private ListPreference mDebugHwRenderer;
311    private ListPreference mLogdSize;
312    private ListPreference mLogpersist;
313    private ListPreference mUsbConfiguration;
314    private ListPreference mTrackFrameTime;
315    private ListPreference mShowNonRectClip;
316    private ListPreference mWindowAnimationScale;
317    private ListPreference mTransitionAnimationScale;
318    private ListPreference mAnimatorDurationScale;
319    private ListPreference mOverlayDisplayDevices;
320
321    private WebViewAppPreferenceController mWebViewAppPrefController;
322
323    private ListPreference mSimulateColorSpace;
324
325    private SwitchPreference mUSBAudio;
326    private SwitchPreference mImmediatelyDestroyActivities;
327
328    private ListPreference mAppProcessLimit;
329
330    private SwitchPreference mShowAllANRs;
331
332    private ColorModePreference mColorModePreference;
333
334    private SwitchPreference mForceResizable;
335
336    private SwitchPreference mColorTemperaturePreference;
337
338    private final ArrayList<Preference> mAllPrefs = new ArrayList<Preference>();
339
340    private final ArrayList<SwitchPreference> mResetSwitchPrefs
341            = new ArrayList<SwitchPreference>();
342
343    private final HashSet<Preference> mDisabledPrefs = new HashSet<Preference>();
344    // To track whether a confirmation dialog was clicked.
345    private boolean mDialogClicked;
346    private Dialog mEnableDialog;
347    private Dialog mAdbDialog;
348
349    private Dialog mAdbKeysDialog;
350    private boolean mUnavailable;
351
352    private boolean mLogpersistCleared;
353    private Dialog mLogpersistClearDialog;
354    private DashboardFeatureProvider mDashboardFeatureProvider;
355    private DevelopmentSettingsEnabler mSettingsEnabler;
356    private BugReportPreferenceController mBugReportController;
357    private BugReportInPowerPreferenceController mBugReportInPowerController;
358    private TelephonyMonitorPreferenceController mTelephonyMonitorController;
359
360    public DevelopmentSettings() {
361        super(UserManager.DISALLOW_DEBUGGING_FEATURES);
362    }
363
364    @Override
365    public int getMetricsCategory() {
366        return MetricsEvent.DEVELOPMENT;
367    }
368
369    @Override
370    public void onAttach(Context context) {
371        super.onAttach(context);
372        mSettingsEnabler = new DevelopmentSettingsEnabler(context, getLifecycle());
373        mDashboardFeatureProvider = FeatureFactory.getFactory(context)
374                .getDashboardFeatureProvider(context);
375    }
376
377    @Override
378    public void onCreate(Bundle icicle) {
379        super.onCreate(icicle);
380
381        mWindowManager = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
382        mBackupManager = IBackupManager.Stub.asInterface(
383                ServiceManager.getService(Context.BACKUP_SERVICE));
384        mWebViewUpdateService = WebViewFactory.getUpdateService();
385        mOemLockManager = (OemLockManager) getSystemService(Context.OEM_LOCK_SERVICE);
386        mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
387
388        mUm = (UserManager) getSystemService(Context.USER_SERVICE);
389
390        mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
391
392        mBugReportController = new BugReportPreferenceController(getActivity());
393        mBugReportInPowerController = new BugReportInPowerPreferenceController(getActivity());
394        mTelephonyMonitorController = new TelephonyMonitorPreferenceController(getActivity());
395        mWebViewAppPrefController = new WebViewAppPreferenceController(getActivity());
396
397        setIfOnlyAvailableForAdmins(true);
398        if (isUiRestricted() || !Utils.isDeviceProvisioned(getActivity())) {
399            // Block access to developer options if the user is not the owner, if user policy
400            // restricts it, or if the device has not been provisioned
401            mUnavailable = true;
402            addPreferencesFromResource(R.xml.empty_settings);
403            return;
404        }
405
406        addPreferencesFromResource(R.xml.development_prefs);
407
408        final PreferenceGroup debugDebuggingCategory = (PreferenceGroup)
409                findPreference(DEBUG_DEBUGGING_CATEGORY_KEY);
410        mEnableAdb = findAndInitSwitchPref(ENABLE_ADB);
411        mClearAdbKeys = findPreference(CLEAR_ADB_KEYS);
412        if (!SystemProperties.getBoolean("ro.adb.secure", false)) {
413            if (debugDebuggingCategory != null) {
414                debugDebuggingCategory.removePreference(mClearAdbKeys);
415            }
416        }
417        mAllPrefs.add(mClearAdbKeys);
418        mEnableTerminal = findAndInitSwitchPref(ENABLE_TERMINAL);
419        if (!isPackageInstalled(getActivity(), TERMINAL_APP_PACKAGE)) {
420            debugDebuggingCategory.removePreference(mEnableTerminal);
421            mEnableTerminal = null;
422        }
423
424        mBugReportController.displayPreference(getPreferenceScreen());
425        mBugReportInPowerController.displayPreference(getPreferenceScreen());
426        mTelephonyMonitorController.displayPreference(getPreferenceScreen());
427        mWebViewAppPrefController.displayPreference(getPreferenceScreen());
428
429        mKeepScreenOn = (RestrictedSwitchPreference) findAndInitSwitchPref(KEEP_SCREEN_ON);
430        mBtHciSnoopLog = findAndInitSwitchPref(BT_HCI_SNOOP_LOG);
431        mEnableOemUnlock = (RestrictedSwitchPreference) findAndInitSwitchPref(ENABLE_OEM_UNLOCK);
432        if (!showEnableOemUnlockPreference(getActivity())) {
433            removePreference(mEnableOemUnlock);
434            mEnableOemUnlock = null;
435        }
436
437        mDebugViewAttributes = findAndInitSwitchPref(DEBUG_VIEW_ATTRIBUTES);
438        mForceAllowOnExternal = findAndInitSwitchPref(FORCE_ALLOW_ON_EXTERNAL_KEY);
439        mPassword = findPreference(LOCAL_BACKUP_PASSWORD);
440        mAllPrefs.add(mPassword);
441
442        if (!mUm.isAdminUser()) {
443            disableForUser(mEnableAdb);
444            disableForUser(mClearAdbKeys);
445            disableForUser(mEnableTerminal);
446            disableForUser(mPassword);
447        }
448
449        mDebugAppPref = findPreference(DEBUG_APP_KEY);
450        mAllPrefs.add(mDebugAppPref);
451        mWaitForDebugger = findAndInitSwitchPref(WAIT_FOR_DEBUGGER_KEY);
452
453        mMockLocationAppPref = findPreference(MOCK_LOCATION_APP_KEY);
454        mAllPrefs.add(mMockLocationAppPref);
455
456        mVerifyAppsOverUsb = findAndInitSwitchPref(VERIFY_APPS_OVER_USB_KEY);
457        if (!showVerifierSetting()) {
458            if (debugDebuggingCategory != null) {
459                debugDebuggingCategory.removePreference(mVerifyAppsOverUsb);
460            } else {
461                mVerifyAppsOverUsb.setEnabled(false);
462            }
463        }
464        mStrictMode = findAndInitSwitchPref(STRICT_MODE_KEY);
465        mPointerLocation = findAndInitSwitchPref(POINTER_LOCATION_KEY);
466        mShowTouches = findAndInitSwitchPref(SHOW_TOUCHES_KEY);
467        mShowScreenUpdates = findAndInitSwitchPref(SHOW_SCREEN_UPDATES_KEY);
468        mDisableOverlays = findAndInitSwitchPref(DISABLE_OVERLAYS_KEY);
469        mForceHardwareUi = findAndInitSwitchPref(FORCE_HARDWARE_UI_KEY);
470        mForceMsaa = findAndInitSwitchPref(FORCE_MSAA_KEY);
471        mTrackFrameTime = addListPreference(TRACK_FRAME_TIME_KEY);
472        mShowNonRectClip = addListPreference(SHOW_NON_RECTANGULAR_CLIP_KEY);
473        mShowHwScreenUpdates = findAndInitSwitchPref(SHOW_HW_SCREEN_UPDATES_KEY);
474        mShowHwLayersUpdates = findAndInitSwitchPref(SHOW_HW_LAYERS_UPDATES_KEY);
475        mDebugLayout = findAndInitSwitchPref(DEBUG_LAYOUT_KEY);
476        mForceRtlLayout = findAndInitSwitchPref(FORCE_RTL_LAYOUT_KEY);
477        mDebugHwOverdraw = addListPreference(DEBUG_HW_OVERDRAW_KEY);
478        mDebugHwRenderer = addListPreference(DEBUG_HW_RENDERER_KEY);
479        mWifiDisplayCertification = findAndInitSwitchPref(WIFI_DISPLAY_CERTIFICATION_KEY);
480        mWifiVerboseLogging = findAndInitSwitchPref(WIFI_VERBOSE_LOGGING_KEY);
481        mWifiAggressiveHandover = findAndInitSwitchPref(WIFI_AGGRESSIVE_HANDOVER_KEY);
482        mWifiAllowScansWithTraffic = findAndInitSwitchPref(WIFI_ALLOW_SCAN_WITH_TRAFFIC_KEY);
483        mMobileDataAlwaysOn = findAndInitSwitchPref(MOBILE_DATA_ALWAYS_ON);
484        mLogdSize = addListPreference(SELECT_LOGD_SIZE_KEY);
485        if ("1".equals(SystemProperties.get("ro.debuggable", "0"))) {
486            mLogpersist = addListPreference(SELECT_LOGPERSIST_KEY);
487        } else {
488            mLogpersist = (ListPreference) findPreference(SELECT_LOGPERSIST_KEY);
489            if (mLogpersist != null) {
490                mLogpersist.setEnabled(false);
491                if (debugDebuggingCategory != null) {
492                    debugDebuggingCategory.removePreference(mLogpersist);
493                }
494            }
495            mLogpersist = null;
496        }
497        mUsbConfiguration = addListPreference(USB_CONFIGURATION_KEY);
498        mBluetoothDisableAbsVolume = findAndInitSwitchPref(BLUETOOTH_DISABLE_ABSOLUTE_VOLUME_KEY);
499        mBluetoothEnableInbandRinging = findAndInitSwitchPref(BLUETOOTH_ENABLE_INBAND_RINGING_KEY);
500        if (!BluetoothHeadset.isInbandRingingSupported(getContext())) {
501            removePreference(mBluetoothEnableInbandRinging);
502            mBluetoothEnableInbandRinging = null;
503        }
504
505        mBluetoothSelectAvrcpVersion = addListPreference(BLUETOOTH_SELECT_AVRCP_VERSION_KEY);
506        mBluetoothSelectA2dpCodec = addListPreference(BLUETOOTH_SELECT_A2DP_CODEC_KEY);
507        mBluetoothSelectA2dpSampleRate = addListPreference(BLUETOOTH_SELECT_A2DP_SAMPLE_RATE_KEY);
508        mBluetoothSelectA2dpBitsPerSample = addListPreference(BLUETOOTH_SELECT_A2DP_BITS_PER_SAMPLE_KEY);
509        mBluetoothSelectA2dpChannelMode = addListPreference(BLUETOOTH_SELECT_A2DP_CHANNEL_MODE_KEY);
510        mBluetoothSelectA2dpLdacPlaybackQuality = addListPreference(BLUETOOTH_SELECT_A2DP_LDAC_PLAYBACK_QUALITY_KEY);
511        initBluetoothConfigurationValues();
512
513        mWindowAnimationScale = addListPreference(WINDOW_ANIMATION_SCALE_KEY);
514        mTransitionAnimationScale = addListPreference(TRANSITION_ANIMATION_SCALE_KEY);
515        mAnimatorDurationScale = addListPreference(ANIMATOR_DURATION_SCALE_KEY);
516        mOverlayDisplayDevices = addListPreference(OVERLAY_DISPLAY_DEVICES_KEY);
517        mSimulateColorSpace = addListPreference(SIMULATE_COLOR_SPACE);
518        mUSBAudio = findAndInitSwitchPref(USB_AUDIO_KEY);
519        mForceResizable = findAndInitSwitchPref(FORCE_RESIZABLE_KEY);
520
521        mImmediatelyDestroyActivities = (SwitchPreference) findPreference(
522                IMMEDIATELY_DESTROY_ACTIVITIES_KEY);
523        mAllPrefs.add(mImmediatelyDestroyActivities);
524        mResetSwitchPrefs.add(mImmediatelyDestroyActivities);
525
526        mAppProcessLimit = addListPreference(APP_PROCESS_LIMIT_KEY);
527
528        mShowAllANRs = (SwitchPreference) findPreference(
529                SHOW_ALL_ANRS_KEY);
530        mAllPrefs.add(mShowAllANRs);
531        mResetSwitchPrefs.add(mShowAllANRs);
532
533        Preference hdcpChecking = findPreference(HDCP_CHECKING_KEY);
534        if (hdcpChecking != null) {
535            mAllPrefs.add(hdcpChecking);
536            removePreferenceForProduction(hdcpChecking);
537        }
538
539        Preference convertFbePreference = findPreference(KEY_CONVERT_FBE);
540
541        try {
542            IBinder service = ServiceManager.getService("mount");
543            IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
544            if (!storageManager.isConvertibleToFBE()) {
545                removePreference(KEY_CONVERT_FBE);
546            } else if ("file".equals(SystemProperties.get("ro.crypto.type", "none"))) {
547                convertFbePreference.setEnabled(false);
548                convertFbePreference.setSummary(getResources()
549                        .getString(R.string.convert_to_file_encryption_done));
550            }
551        } catch (RemoteException e) {
552            removePreference(KEY_CONVERT_FBE);
553        }
554
555        mOtaDisableAutomaticUpdate = findAndInitSwitchPref(OTA_DISABLE_AUTOMATIC_UPDATE_KEY);
556
557        mColorModePreference = (ColorModePreference) findPreference(KEY_COLOR_MODE);
558        mColorModePreference.updateCurrentAndSupported();
559        if (mColorModePreference.getColorModeCount() < 2) {
560            removePreference(KEY_COLOR_MODE);
561            mColorModePreference = null;
562        }
563
564        mColorTemperaturePreference = (SwitchPreference) findPreference(COLOR_TEMPERATURE_KEY);
565        if (getResources().getBoolean(R.bool.config_enableColorTemperature)) {
566            mAllPrefs.add(mColorTemperaturePreference);
567            mResetSwitchPrefs.add(mColorTemperaturePreference);
568        } else {
569            removePreference(COLOR_TEMPERATURE_KEY);
570            mColorTemperaturePreference = null;
571        }
572
573        addDashboardCategoryPreferences();
574    }
575
576    @VisibleForTesting
577    void addDashboardCategoryPreferences() {
578        final PreferenceScreen screen = getPreferenceScreen();
579        final List<Preference> tilePrefs = mDashboardFeatureProvider.getPreferencesForCategory(
580                getActivity(), getPrefContext(), getMetricsCategory(),
581                CategoryKey.CATEGORY_SYSTEM_DEVELOPMENT);
582        if (tilePrefs != null) {
583            for (Preference preference : tilePrefs) {
584                screen.addPreference(preference);
585            }
586        }
587    }
588
589    private ListPreference addListPreference(String prefKey) {
590        ListPreference pref = (ListPreference) findPreference(prefKey);
591        mAllPrefs.add(pref);
592        pref.setOnPreferenceChangeListener(this);
593        return pref;
594    }
595
596    private void disableForUser(Preference pref) {
597        if (pref != null) {
598            pref.setEnabled(false);
599            mDisabledPrefs.add(pref);
600        }
601    }
602
603    private SwitchPreference findAndInitSwitchPref(String key) {
604        SwitchPreference pref = (SwitchPreference) findPreference(key);
605        if (pref == null) {
606            throw new IllegalArgumentException("Cannot find preference with key = " + key);
607        }
608        mAllPrefs.add(pref);
609        mResetSwitchPrefs.add(pref);
610        return pref;
611    }
612
613    @Override
614    public void onActivityCreated(Bundle savedInstanceState) {
615        super.onActivityCreated(savedInstanceState);
616
617        final SettingsActivity activity = (SettingsActivity) getActivity();
618
619        mSwitchBar = activity.getSwitchBar();
620        if (mUnavailable) {
621            mSwitchBar.setEnabled(false);
622            return;
623        }
624
625        mSwitchBar.addOnSwitchChangeListener(this);
626    }
627
628    private boolean removePreferenceForProduction(Preference preference) {
629        if ("user".equals(Build.TYPE)) {
630            removePreference(preference);
631            return true;
632        }
633        return false;
634    }
635
636    private void removePreference(Preference preference) {
637        getPreferenceScreen().removePreference(preference);
638        mAllPrefs.remove(preference);
639        mResetSwitchPrefs.remove(preference);
640    }
641
642    private void setPrefsEnabledState(boolean enabled) {
643        for (int i = 0; i < mAllPrefs.size(); i++) {
644            Preference pref = mAllPrefs.get(i);
645            pref.setEnabled(enabled && !mDisabledPrefs.contains(pref));
646        }
647        mBugReportInPowerController.enablePreference(enabled);
648        mTelephonyMonitorController.enablePreference(enabled);
649        mWebViewAppPrefController.enablePreference(enabled);
650        updateAllOptions();
651    }
652
653    @Override
654    public void onResume() {
655        super.onResume();
656
657        if (mUnavailable) {
658            // Show error message
659            if (!isUiRestrictedByOnlyAdmin()) {
660                getEmptyTextView().setText(R.string.development_settings_not_available);
661            }
662            getPreferenceScreen().removeAll();
663            return;
664        }
665
666        // A DeviceAdmin has specified a maximum time until the device
667        // will lock...  in this case we can't allow the user to turn
668        // on "stay awake when plugged in" because that would defeat the
669        // restriction.
670        final EnforcedAdmin admin = RestrictedLockUtils.checkIfMaximumTimeToLockIsSet(
671                getActivity());
672        mKeepScreenOn.setDisabledByAdmin(admin);
673        if (admin == null) {
674            mDisabledPrefs.remove(mKeepScreenOn);
675        } else {
676            mDisabledPrefs.add(mKeepScreenOn);
677        }
678
679        final boolean lastEnabledState = mSettingsEnabler.getLastEnabledState();
680        mSwitchBar.setChecked(lastEnabledState);
681        setPrefsEnabledState(lastEnabledState);
682
683        if (mHaveDebugSettings && !lastEnabledState) {
684            // Overall debugging is disabled, but there are some debug
685            // settings that are enabled.  This is an invalid state.  Switch
686            // to debug settings being enabled, so the user knows there is
687            // stuff enabled and can turn it all off if they want.
688            mSettingsEnabler.enableDevelopmentSettings();
689            mSwitchBar.setChecked(lastEnabledState);
690            setPrefsEnabledState(lastEnabledState);
691        }
692        mSwitchBar.show();
693
694        if (mColorModePreference != null) {
695            mColorModePreference.startListening();
696            mColorModePreference.updateCurrentAndSupported();
697        }
698    }
699
700    @Override
701    public void onPause() {
702        super.onPause();
703        if (mColorModePreference != null) {
704            mColorModePreference.stopListening();
705        }
706    }
707
708    @Override
709    public View onCreateView(LayoutInflater inflater, ViewGroup container,
710            Bundle savedInstanceState) {
711        IntentFilter filter = new IntentFilter();
712        filter.addAction(UsbManager.ACTION_USB_STATE);
713        if (getActivity().registerReceiver(mUsbReceiver, filter) == null) {
714            updateUsbConfigurationValues();
715        }
716
717        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
718        if (adapter != null) {
719            adapter.getProfileProxy(getActivity(),
720                                    mBluetoothA2dpServiceListener,
721                                    BluetoothProfile.A2DP);
722        }
723        filter = new IntentFilter();
724        filter.addAction(BluetoothA2dp.ACTION_CODEC_CONFIG_CHANGED);
725        if (getActivity().registerReceiver(mBluetoothA2dpReceiver, filter) == null) {
726            updateBluetoothA2dpConfigurationValues();
727        }
728
729        return super.onCreateView(inflater, container, savedInstanceState);
730    }
731
732    @Override
733    public void onDestroyView() {
734        super.onDestroyView();
735
736        if (mUnavailable) {
737            return;
738        }
739        mSwitchBar.removeOnSwitchChangeListener(this);
740        mSwitchBar.hide();
741        getActivity().unregisterReceiver(mUsbReceiver);
742        getActivity().unregisterReceiver(mBluetoothA2dpReceiver);
743        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
744        if (adapter != null) {
745            adapter.closeProfileProxy(BluetoothProfile.A2DP, mBluetoothA2dp);
746            mBluetoothA2dp = null;
747        }
748    }
749
750    void updateSwitchPreference(SwitchPreference switchPreference, boolean value) {
751        switchPreference.setChecked(value);
752        mHaveDebugSettings |= value;
753    }
754
755    private void updateAllOptions() {
756        final Context context = getActivity();
757        final ContentResolver cr = context.getContentResolver();
758        mHaveDebugSettings = false;
759        updateSwitchPreference(mEnableAdb, Settings.Global.getInt(cr,
760                Settings.Global.ADB_ENABLED, 0) != 0);
761        if (mEnableTerminal != null) {
762            updateSwitchPreference(mEnableTerminal,
763                    context.getPackageManager().getApplicationEnabledSetting(TERMINAL_APP_PACKAGE)
764                            == PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
765        }
766        mHaveDebugSettings |= mBugReportInPowerController.updatePreference();
767        mHaveDebugSettings |= mTelephonyMonitorController.updatePreference();
768        updateSwitchPreference(mKeepScreenOn, Settings.Global.getInt(cr,
769                Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0) != 0);
770        updateSwitchPreference(mBtHciSnoopLog, SystemProperties.getBoolean(
771                BLUETOOTH_BTSNOOP_ENABLE_PROPERTY, false));
772        updateSwitchPreference(mDebugViewAttributes, Settings.Global.getInt(cr,
773                Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0);
774        updateSwitchPreference(mForceAllowOnExternal, Settings.Global.getInt(cr,
775                Settings.Global.FORCE_ALLOW_ON_EXTERNAL, 0) != 0);
776        updateHdcpValues();
777        updatePasswordSummary();
778        updateDebuggerOptions();
779        updateMockLocation();
780        updateStrictModeVisualOptions();
781        updatePointerLocationOptions();
782        updateShowTouchesOptions();
783        updateFlingerOptions();
784        updateHardwareUiOptions();
785        updateMsaaOptions();
786        updateTrackFrameTimeOptions();
787        updateShowNonRectClipOptions();
788        updateShowHwScreenUpdatesOptions();
789        updateShowHwLayersUpdatesOptions();
790        updateDebugHwOverdrawOptions();
791        updateDebugHwRendererOptions();
792        updateDebugLayoutOptions();
793        updateAnimationScaleOptions();
794        updateOverlayDisplayDevicesOptions();
795        updateImmediatelyDestroyActivitiesOptions();
796        updateAppProcessLimitOptions();
797        updateShowAllANRsOptions();
798        updateVerifyAppsOverUsbOptions();
799        updateOtaDisableAutomaticUpdateOptions();
800        updateBugreportOptions();
801        updateForceRtlOptions();
802        updateLogdSizeValues();
803        updateLogpersistValues();
804        updateWifiDisplayCertificationOptions();
805        updateWifiVerboseLoggingOptions();
806        updateWifiAggressiveHandoverOptions();
807        updateWifiAllowScansWithTrafficOptions();
808        updateMobileDataAlwaysOnOptions();
809        updateSimulateColorSpace();
810        updateUSBAudioOptions();
811        updateForceResizableOptions();
812        Preference webViewAppPref = findPreference(mWebViewAppPrefController.getPreferenceKey());
813        mWebViewAppPrefController.updateState(webViewAppPref);
814        updateOemUnlockOptions();
815        if (mColorTemperaturePreference != null) {
816            updateColorTemperature();
817        }
818        updateBluetoothDisableAbsVolumeOptions();
819        updateBluetoothEnableInbandRingingOptions();
820        updateBluetoothA2dpConfigurationValues();
821    }
822
823    private void resetDangerousOptions() {
824        mDontPokeProperties = true;
825        for (int i = 0; i < mResetSwitchPrefs.size(); i++) {
826            SwitchPreference cb = mResetSwitchPrefs.get(i);
827            if (cb.isChecked()) {
828                cb.setChecked(false);
829                onPreferenceTreeClick(cb);
830            }
831        }
832        mBugReportInPowerController.resetPreference();
833        resetDebuggerOptions();
834        writeLogpersistOption(null, true);
835        writeLogdSizeOption(null);
836        writeAnimationScaleOption(0, mWindowAnimationScale, null);
837        writeAnimationScaleOption(1, mTransitionAnimationScale, null);
838        writeAnimationScaleOption(2, mAnimatorDurationScale, null);
839        // Only poke the color space setting if we control it.
840        if (usingDevelopmentColorSpace()) {
841            writeSimulateColorSpace(-1);
842        }
843        writeOverlayDisplayDevicesOptions(null);
844        writeAppProcessLimitOptions(null);
845        mHaveDebugSettings = false;
846        updateAllOptions();
847        mDontPokeProperties = false;
848        pokeSystemProperties();
849    }
850
851    private void updateHdcpValues() {
852        ListPreference hdcpChecking = (ListPreference) findPreference(HDCP_CHECKING_KEY);
853        if (hdcpChecking != null) {
854            String currentValue = SystemProperties.get(HDCP_CHECKING_PROPERTY);
855            String[] values = getResources().getStringArray(R.array.hdcp_checking_values);
856            String[] summaries = getResources().getStringArray(R.array.hdcp_checking_summaries);
857            int index = 1; // Defaults to drm-only. Needs to match with R.array.hdcp_checking_values
858            for (int i = 0; i < values.length; i++) {
859                if (currentValue.equals(values[i])) {
860                    index = i;
861                    break;
862                }
863            }
864            hdcpChecking.setValue(values[index]);
865            hdcpChecking.setSummary(summaries[index]);
866            hdcpChecking.setOnPreferenceChangeListener(this);
867        }
868    }
869
870    private void updatePasswordSummary() {
871        try {
872            if (mBackupManager.hasBackupPassword()) {
873                mPassword.setSummary(R.string.local_backup_password_summary_change);
874            } else {
875                mPassword.setSummary(R.string.local_backup_password_summary_none);
876            }
877        } catch (RemoteException e) {
878            // Not much we can do here
879        }
880    }
881
882    private void writeBtHciSnoopLogOptions() {
883        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
884        SystemProperties.set(BLUETOOTH_BTSNOOP_ENABLE_PROPERTY,
885                Boolean.toString(mBtHciSnoopLog.isChecked()));
886    }
887
888    private void writeDebuggerOptions() {
889        try {
890            ActivityManager.getService().setDebugApp(
891                    mDebugApp, mWaitForDebugger.isChecked(), true);
892        } catch (RemoteException ex) {
893        }
894    }
895
896    private void writeMockLocation() {
897        AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
898
899        // Disable the app op of the previous mock location app if such.
900        List<PackageOps> packageOps = appOpsManager.getPackagesForOps(MOCK_LOCATION_APP_OPS);
901        if (packageOps != null) {
902            // Should be one but in case we are in a bad state due to use of command line tools.
903            for (PackageOps packageOp : packageOps) {
904                if (packageOp.getOps().get(0).getMode() != AppOpsManager.MODE_ERRORED) {
905                    String oldMockLocationApp = packageOp.getPackageName();
906                    try {
907                        ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(
908                                oldMockLocationApp, PackageManager.GET_DISABLED_COMPONENTS);
909                        appOpsManager.setMode(AppOpsManager.OP_MOCK_LOCATION, ai.uid,
910                                oldMockLocationApp, AppOpsManager.MODE_ERRORED);
911                    } catch (NameNotFoundException e) {
912                        /* ignore */
913                    }
914                }
915            }
916        }
917
918        // Enable the app op of the new mock location app if such.
919        if (!TextUtils.isEmpty(mMockLocationApp)) {
920            try {
921                ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(
922                        mMockLocationApp, PackageManager.GET_DISABLED_COMPONENTS);
923                appOpsManager.setMode(AppOpsManager.OP_MOCK_LOCATION, ai.uid,
924                        mMockLocationApp, AppOpsManager.MODE_ALLOWED);
925            } catch (NameNotFoundException e) {
926                /* ignore */
927            }
928        }
929    }
930
931    private static void resetDebuggerOptions() {
932        try {
933            ActivityManager.getService().setDebugApp(
934                    null, false, true);
935        } catch (RemoteException ex) {
936        }
937    }
938
939    private void updateDebuggerOptions() {
940        mDebugApp = Settings.Global.getString(
941                getActivity().getContentResolver(), Settings.Global.DEBUG_APP);
942        updateSwitchPreference(mWaitForDebugger, Settings.Global.getInt(
943                getActivity().getContentResolver(), Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0);
944        if (mDebugApp != null && mDebugApp.length() > 0) {
945            String label;
946            try {
947                ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(mDebugApp,
948                        PackageManager.GET_DISABLED_COMPONENTS);
949                CharSequence lab = getActivity().getPackageManager().getApplicationLabel(ai);
950                label = lab != null ? lab.toString() : mDebugApp;
951            } catch (PackageManager.NameNotFoundException e) {
952                label = mDebugApp;
953            }
954            mDebugAppPref.setSummary(getResources().getString(R.string.debug_app_set, label));
955            mWaitForDebugger.setEnabled(true);
956            mHaveDebugSettings = true;
957        } else {
958            mDebugAppPref.setSummary(getResources().getString(R.string.debug_app_not_set));
959            mWaitForDebugger.setEnabled(false);
960        }
961    }
962
963    private void updateMockLocation() {
964        AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
965
966        List<PackageOps> packageOps = appOpsManager.getPackagesForOps(MOCK_LOCATION_APP_OPS);
967        if (packageOps != null) {
968            for (PackageOps packageOp : packageOps) {
969                if (packageOp.getOps().get(0).getMode() == AppOpsManager.MODE_ALLOWED) {
970                    mMockLocationApp = packageOps.get(0).getPackageName();
971                    break;
972                }
973            }
974        }
975
976        if (!TextUtils.isEmpty(mMockLocationApp)) {
977            String label = mMockLocationApp;
978            try {
979                ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(
980                        mMockLocationApp, PackageManager.GET_DISABLED_COMPONENTS);
981                CharSequence appLabel = getPackageManager().getApplicationLabel(ai);
982                if (appLabel != null) {
983                    label = appLabel.toString();
984                }
985            } catch (PackageManager.NameNotFoundException e) {
986                /* ignore */
987            }
988
989            mMockLocationAppPref.setSummary(getString(R.string.mock_location_app_set, label));
990            mHaveDebugSettings = true;
991        } else {
992            mMockLocationAppPref.setSummary(getString(R.string.mock_location_app_not_set));
993        }
994    }
995
996    private void updateVerifyAppsOverUsbOptions() {
997        updateSwitchPreference(mVerifyAppsOverUsb,
998                Settings.Global.getInt(getActivity().getContentResolver(),
999                        Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) != 0);
1000        mVerifyAppsOverUsb.setEnabled(enableVerifierSetting());
1001    }
1002
1003    private void writeVerifyAppsOverUsbOptions() {
1004        Settings.Global.putInt(getActivity().getContentResolver(),
1005                Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB,
1006                mVerifyAppsOverUsb.isChecked() ? 1 : 0);
1007    }
1008
1009    private void updateOtaDisableAutomaticUpdateOptions() {
1010        // We use the "disabled status" in code, but show the opposite text
1011        // "Automatic system updates" on screen. So a value 0 indicates the
1012        // automatic update is enabled.
1013        updateSwitchPreference(mOtaDisableAutomaticUpdate, Settings.Global.getInt(
1014                getActivity().getContentResolver(),
1015                Settings.Global.OTA_DISABLE_AUTOMATIC_UPDATE, 0) != 1);
1016    }
1017
1018    private void writeOtaDisableAutomaticUpdateOptions() {
1019        // We use the "disabled status" in code, but show the opposite text
1020        // "Automatic system updates" on screen. So a value 0 indicates the
1021        // automatic update is enabled.
1022        Settings.Global.putInt(getActivity().getContentResolver(),
1023                Settings.Global.OTA_DISABLE_AUTOMATIC_UPDATE,
1024                mOtaDisableAutomaticUpdate.isChecked() ? 0 : 1);
1025    }
1026
1027    private boolean enableVerifierSetting() {
1028        final ContentResolver cr = getActivity().getContentResolver();
1029        if (Settings.Global.getInt(cr, Settings.Global.ADB_ENABLED, 0) == 0) {
1030            return false;
1031        }
1032        if (Settings.Global.getInt(cr, Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 0) {
1033            return false;
1034        } else {
1035            final PackageManager pm = getActivity().getPackageManager();
1036            final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1037            verification.setType(PACKAGE_MIME_TYPE);
1038            verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1039            final List<ResolveInfo> receivers = pm.queryBroadcastReceivers(verification, 0);
1040            if (receivers.size() == 0) {
1041                return false;
1042            }
1043        }
1044        return true;
1045    }
1046
1047    private boolean showVerifierSetting() {
1048        return Settings.Global.getInt(getActivity().getContentResolver(),
1049                Settings.Global.PACKAGE_VERIFIER_SETTING_VISIBLE, 1) > 0;
1050    }
1051
1052    private static boolean showEnableOemUnlockPreference(Context context) {
1053        return context.getSystemService(Context.OEM_LOCK_SERVICE) != null;
1054    }
1055
1056    private boolean enableOemUnlockPreference() {
1057        return !isBootloaderUnlocked() && mOemLockManager.canUserAllowOemUnlock();
1058    }
1059
1060    private void updateOemUnlockOptions() {
1061        if (mEnableOemUnlock != null) {
1062            updateSwitchPreference(mEnableOemUnlock, mOemLockManager.isOemUnlockAllowed());
1063            updateOemUnlockSettingDescription();
1064            // Showing mEnableOemUnlock preference as device has persistent data block.
1065            mEnableOemUnlock.setDisabledByAdmin(null);
1066            mEnableOemUnlock.setEnabled(enableOemUnlockPreference());
1067            if (mEnableOemUnlock.isEnabled()) {
1068                // Check restriction, disable mEnableOemUnlock and apply policy transparency.
1069                mEnableOemUnlock.checkRestrictionAndSetDisabled(UserManager.DISALLOW_FACTORY_RESET);
1070            }
1071            if (mEnableOemUnlock.isEnabled()) {
1072                // Check restriction, disable mEnableOemUnlock and apply policy transparency.
1073                mEnableOemUnlock.checkRestrictionAndSetDisabled(UserManager.DISALLOW_OEM_UNLOCK);
1074            }
1075        }
1076    }
1077
1078    private void updateBugreportOptions() {
1079        mBugReportController.enablePreference(true);
1080        mBugReportInPowerController.updateBugreportOptions();
1081    }
1082
1083    // Returns the current state of the system property that controls
1084    // strictmode flashes.  One of:
1085    //    0: not explicitly set one way or another
1086    //    1: on
1087    //    2: off
1088    private static int currentStrictModeActiveIndex() {
1089        if (TextUtils.isEmpty(SystemProperties.get(StrictMode.VISUAL_PROPERTY))) {
1090            return 0;
1091        }
1092        boolean enabled = SystemProperties.getBoolean(StrictMode.VISUAL_PROPERTY, false);
1093        return enabled ? 1 : 2;
1094    }
1095
1096    private void writeStrictModeVisualOptions() {
1097        try {
1098            mWindowManager.setStrictModeVisualIndicatorPreference(mStrictMode.isChecked()
1099                    ? "1" : "");
1100        } catch (RemoteException e) {
1101        }
1102    }
1103
1104    private void updateStrictModeVisualOptions() {
1105        updateSwitchPreference(mStrictMode, currentStrictModeActiveIndex() == 1);
1106    }
1107
1108    private void writePointerLocationOptions() {
1109        Settings.System.putInt(getActivity().getContentResolver(),
1110                Settings.System.POINTER_LOCATION, mPointerLocation.isChecked() ? 1 : 0);
1111    }
1112
1113    private void updatePointerLocationOptions() {
1114        updateSwitchPreference(mPointerLocation,
1115                Settings.System.getInt(getActivity().getContentResolver(),
1116                        Settings.System.POINTER_LOCATION, 0) != 0);
1117    }
1118
1119    private void writeShowTouchesOptions() {
1120        Settings.System.putInt(getActivity().getContentResolver(),
1121                Settings.System.SHOW_TOUCHES, mShowTouches.isChecked() ? 1 : 0);
1122    }
1123
1124    private void updateShowTouchesOptions() {
1125        updateSwitchPreference(mShowTouches,
1126                Settings.System.getInt(getActivity().getContentResolver(),
1127                        Settings.System.SHOW_TOUCHES, 0) != 0);
1128    }
1129
1130    private void updateFlingerOptions() {
1131        // magic communication with surface flinger.
1132        try {
1133            IBinder flinger = ServiceManager.getService("SurfaceFlinger");
1134            if (flinger != null) {
1135                Parcel data = Parcel.obtain();
1136                Parcel reply = Parcel.obtain();
1137                data.writeInterfaceToken("android.ui.ISurfaceComposer");
1138                flinger.transact(1010, data, reply, 0);
1139                @SuppressWarnings("unused")
1140                int showCpu = reply.readInt();
1141                @SuppressWarnings("unused")
1142                int enableGL = reply.readInt();
1143                int showUpdates = reply.readInt();
1144                updateSwitchPreference(mShowScreenUpdates, showUpdates != 0);
1145                @SuppressWarnings("unused")
1146                int showBackground = reply.readInt();
1147                int disableOverlays = reply.readInt();
1148                updateSwitchPreference(mDisableOverlays, disableOverlays != 0);
1149                reply.recycle();
1150                data.recycle();
1151            }
1152        } catch (RemoteException ex) {
1153        }
1154    }
1155
1156    private void writeShowUpdatesOption() {
1157        try {
1158            IBinder flinger = ServiceManager.getService("SurfaceFlinger");
1159            if (flinger != null) {
1160                Parcel data = Parcel.obtain();
1161                data.writeInterfaceToken("android.ui.ISurfaceComposer");
1162                final int showUpdates = mShowScreenUpdates.isChecked() ? 1 : 0;
1163                data.writeInt(showUpdates);
1164                flinger.transact(1002, data, null, 0);
1165                data.recycle();
1166
1167                updateFlingerOptions();
1168            }
1169        } catch (RemoteException ex) {
1170        }
1171    }
1172
1173    private void writeDisableOverlaysOption() {
1174        try {
1175            IBinder flinger = ServiceManager.getService("SurfaceFlinger");
1176            if (flinger != null) {
1177                Parcel data = Parcel.obtain();
1178                data.writeInterfaceToken("android.ui.ISurfaceComposer");
1179                final int disableOverlays = mDisableOverlays.isChecked() ? 1 : 0;
1180                data.writeInt(disableOverlays);
1181                flinger.transact(1008, data, null, 0);
1182                data.recycle();
1183
1184                updateFlingerOptions();
1185            }
1186        } catch (RemoteException ex) {
1187        }
1188    }
1189
1190    private void updateHardwareUiOptions() {
1191        updateSwitchPreference(mForceHardwareUi,
1192                SystemProperties.getBoolean(HARDWARE_UI_PROPERTY, false));
1193    }
1194
1195    private void writeHardwareUiOptions() {
1196        SystemProperties.set(HARDWARE_UI_PROPERTY, mForceHardwareUi.isChecked() ? "true" : "false");
1197        pokeSystemProperties();
1198    }
1199
1200    private void updateMsaaOptions() {
1201        updateSwitchPreference(mForceMsaa, SystemProperties.getBoolean(MSAA_PROPERTY, false));
1202    }
1203
1204    private void writeMsaaOptions() {
1205        SystemProperties.set(MSAA_PROPERTY, mForceMsaa.isChecked() ? "true" : "false");
1206        pokeSystemProperties();
1207    }
1208
1209    private void updateTrackFrameTimeOptions() {
1210        String value = SystemProperties.get(ThreadedRenderer.PROFILE_PROPERTY);
1211        if (value == null) {
1212            value = "";
1213        }
1214
1215        CharSequence[] values = mTrackFrameTime.getEntryValues();
1216        for (int i = 0; i < values.length; i++) {
1217            if (value.contentEquals(values[i])) {
1218                mTrackFrameTime.setValueIndex(i);
1219                mTrackFrameTime.setSummary(mTrackFrameTime.getEntries()[i]);
1220                return;
1221            }
1222        }
1223        mTrackFrameTime.setValueIndex(0);
1224        mTrackFrameTime.setSummary(mTrackFrameTime.getEntries()[0]);
1225    }
1226
1227    private void writeTrackFrameTimeOptions(Object newValue) {
1228        SystemProperties.set(ThreadedRenderer.PROFILE_PROPERTY,
1229                newValue == null ? "" : newValue.toString());
1230        pokeSystemProperties();
1231        updateTrackFrameTimeOptions();
1232    }
1233
1234    private void updateShowNonRectClipOptions() {
1235        String value = SystemProperties.get(
1236                ThreadedRenderer.DEBUG_SHOW_NON_RECTANGULAR_CLIP_PROPERTY);
1237        if (value == null) {
1238            value = "hide";
1239        }
1240
1241        CharSequence[] values = mShowNonRectClip.getEntryValues();
1242        for (int i = 0; i < values.length; i++) {
1243            if (value.contentEquals(values[i])) {
1244                mShowNonRectClip.setValueIndex(i);
1245                mShowNonRectClip.setSummary(mShowNonRectClip.getEntries()[i]);
1246                return;
1247            }
1248        }
1249        mShowNonRectClip.setValueIndex(0);
1250        mShowNonRectClip.setSummary(mShowNonRectClip.getEntries()[0]);
1251    }
1252
1253    private void writeShowNonRectClipOptions(Object newValue) {
1254        SystemProperties.set(ThreadedRenderer.DEBUG_SHOW_NON_RECTANGULAR_CLIP_PROPERTY,
1255                newValue == null ? "" : newValue.toString());
1256        pokeSystemProperties();
1257        updateShowNonRectClipOptions();
1258    }
1259
1260    private void updateShowHwScreenUpdatesOptions() {
1261        updateSwitchPreference(mShowHwScreenUpdates,
1262                SystemProperties.getBoolean(ThreadedRenderer.DEBUG_DIRTY_REGIONS_PROPERTY, false));
1263    }
1264
1265    private void writeShowHwScreenUpdatesOptions() {
1266        SystemProperties.set(ThreadedRenderer.DEBUG_DIRTY_REGIONS_PROPERTY,
1267                mShowHwScreenUpdates.isChecked() ? "true" : null);
1268        pokeSystemProperties();
1269    }
1270
1271    private void updateShowHwLayersUpdatesOptions() {
1272        updateSwitchPreference(mShowHwLayersUpdates, SystemProperties.getBoolean(
1273                ThreadedRenderer.DEBUG_SHOW_LAYERS_UPDATES_PROPERTY, false));
1274    }
1275
1276    private void writeShowHwLayersUpdatesOptions() {
1277        SystemProperties.set(ThreadedRenderer.DEBUG_SHOW_LAYERS_UPDATES_PROPERTY,
1278                mShowHwLayersUpdates.isChecked() ? "true" : null);
1279        pokeSystemProperties();
1280    }
1281
1282    private void updateDebugHwOverdrawOptions() {
1283        String value = SystemProperties.get(ThreadedRenderer.DEBUG_OVERDRAW_PROPERTY);
1284        if (value == null) {
1285            value = "";
1286        }
1287
1288        CharSequence[] values = mDebugHwOverdraw.getEntryValues();
1289        for (int i = 0; i < values.length; i++) {
1290            if (value.contentEquals(values[i])) {
1291                mDebugHwOverdraw.setValueIndex(i);
1292                mDebugHwOverdraw.setSummary(mDebugHwOverdraw.getEntries()[i]);
1293                return;
1294            }
1295        }
1296        mDebugHwOverdraw.setValueIndex(0);
1297        mDebugHwOverdraw.setSummary(mDebugHwOverdraw.getEntries()[0]);
1298    }
1299
1300    private void writeDebugHwOverdrawOptions(Object newValue) {
1301        SystemProperties.set(ThreadedRenderer.DEBUG_OVERDRAW_PROPERTY,
1302                newValue == null ? "" : newValue.toString());
1303        pokeSystemProperties();
1304        updateDebugHwOverdrawOptions();
1305    }
1306
1307    private void updateDebugHwRendererOptions() {
1308        String value = SystemProperties.get(ThreadedRenderer.DEBUG_RENDERER_PROPERTY);
1309        if (value == null) {
1310            value = "";
1311        }
1312
1313        CharSequence[] values = mDebugHwRenderer.getEntryValues();
1314        for (int i = 0; i < values.length; i++) {
1315            if (value.contentEquals(values[i])) {
1316                mDebugHwRenderer.setValueIndex(i);
1317                mDebugHwRenderer.setSummary(mDebugHwRenderer.getEntries()[i]);
1318                return;
1319            }
1320        }
1321        mDebugHwRenderer.setValueIndex(0);
1322        mDebugHwRenderer.setSummary(mDebugHwRenderer.getEntries()[0]);
1323    }
1324
1325    private void writeDebugHwRendererOptions(Object newValue) {
1326        SystemProperties.set(ThreadedRenderer.DEBUG_RENDERER_PROPERTY,
1327                newValue == null ? "" : newValue.toString());
1328        pokeSystemProperties();
1329        updateDebugHwRendererOptions();
1330    }
1331
1332    private void updateDebugLayoutOptions() {
1333        updateSwitchPreference(mDebugLayout,
1334                SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false));
1335    }
1336
1337    private void writeDebugLayoutOptions() {
1338        SystemProperties.set(View.DEBUG_LAYOUT_PROPERTY,
1339                mDebugLayout.isChecked() ? "true" : "false");
1340        pokeSystemProperties();
1341    }
1342
1343    private void updateSimulateColorSpace() {
1344        final ContentResolver cr = getContentResolver();
1345        final boolean enabled = Settings.Secure.getInt(
1346                cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 0) != 0;
1347        if (enabled) {
1348            final String mode = Integer.toString(Settings.Secure.getInt(
1349                    cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER,
1350                    AccessibilityManager.DALTONIZER_DISABLED));
1351            mSimulateColorSpace.setValue(mode);
1352            final int index = mSimulateColorSpace.findIndexOfValue(mode);
1353            if (index < 0) {
1354                // We're using a mode controlled by accessibility preferences.
1355                mSimulateColorSpace.setSummary(getString(R.string.daltonizer_type_overridden,
1356                        getString(R.string.accessibility_display_daltonizer_preference_title)));
1357            } else {
1358                mSimulateColorSpace.setSummary("%s");
1359            }
1360        } else {
1361            mSimulateColorSpace.setValue(
1362                    Integer.toString(AccessibilityManager.DALTONIZER_DISABLED));
1363        }
1364    }
1365
1366    /**
1367     * @return <code>true</code> if the color space preference is currently
1368     * controlled by development settings
1369     */
1370    private boolean usingDevelopmentColorSpace() {
1371        final ContentResolver cr = getContentResolver();
1372        final boolean enabled = Settings.Secure.getInt(
1373                cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 0) != 0;
1374        if (enabled) {
1375            final String mode = Integer.toString(Settings.Secure.getInt(
1376                    cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER,
1377                    AccessibilityManager.DALTONIZER_DISABLED));
1378            final int index = mSimulateColorSpace.findIndexOfValue(mode);
1379            if (index >= 0) {
1380                // We're using a mode controlled by developer preferences.
1381                return true;
1382            }
1383        }
1384        return false;
1385    }
1386
1387    private void writeSimulateColorSpace(Object value) {
1388        final ContentResolver cr = getContentResolver();
1389        final int newMode = Integer.parseInt(value.toString());
1390        if (newMode < 0) {
1391            Settings.Secure.putInt(cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 0);
1392        } else {
1393            Settings.Secure.putInt(cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 1);
1394            Settings.Secure.putInt(cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER, newMode);
1395        }
1396    }
1397
1398    private void updateColorTemperature() {
1399        updateSwitchPreference(mColorTemperaturePreference,
1400                SystemProperties.getBoolean(COLOR_TEMPERATURE_PROPERTY, false));
1401    }
1402
1403    private void writeColorTemperature() {
1404        SystemProperties.set(COLOR_TEMPERATURE_PROPERTY,
1405                mColorTemperaturePreference.isChecked() ? "1" : "0");
1406        pokeSystemProperties();
1407        Toast.makeText(getActivity(), R.string.color_temperature_toast, Toast.LENGTH_LONG).show();
1408    }
1409
1410    private void updateUSBAudioOptions() {
1411        updateSwitchPreference(mUSBAudio, Settings.Secure.getInt(getContentResolver(),
1412                Settings.Secure.USB_AUDIO_AUTOMATIC_ROUTING_DISABLED, 0) != 0);
1413    }
1414
1415    private void writeUSBAudioOptions() {
1416        Settings.Secure.putInt(getContentResolver(),
1417                Settings.Secure.USB_AUDIO_AUTOMATIC_ROUTING_DISABLED,
1418                mUSBAudio.isChecked() ? 1 : 0);
1419    }
1420
1421    private void updateForceResizableOptions() {
1422        updateSwitchPreference(mForceResizable, Settings.Global.getInt(getContentResolver(),
1423                Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0);
1424    }
1425
1426    private void writeForceResizableOptions() {
1427        Settings.Global.putInt(getContentResolver(),
1428                Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES,
1429                mForceResizable.isChecked() ? 1 : 0);
1430    }
1431
1432    private void updateForceRtlOptions() {
1433        updateSwitchPreference(mForceRtlLayout,
1434                Settings.Global.getInt(getActivity().getContentResolver(),
1435                        Settings.Global.DEVELOPMENT_FORCE_RTL, 0) != 0);
1436    }
1437
1438    private void writeForceRtlOptions() {
1439        boolean value = mForceRtlLayout.isChecked();
1440        Settings.Global.putInt(getActivity().getContentResolver(),
1441                Settings.Global.DEVELOPMENT_FORCE_RTL, value ? 1 : 0);
1442        SystemProperties.set(Settings.Global.DEVELOPMENT_FORCE_RTL, value ? "1" : "0");
1443        LocalePicker.updateLocales(getActivity().getResources().getConfiguration().getLocales());
1444    }
1445
1446    private void updateWifiDisplayCertificationOptions() {
1447        updateSwitchPreference(mWifiDisplayCertification, Settings.Global.getInt(
1448                getActivity().getContentResolver(),
1449                Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON, 0) != 0);
1450    }
1451
1452    private void writeWifiDisplayCertificationOptions() {
1453        Settings.Global.putInt(getActivity().getContentResolver(),
1454                Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON,
1455                mWifiDisplayCertification.isChecked() ? 1 : 0);
1456    }
1457
1458    private void updateWifiVerboseLoggingOptions() {
1459        boolean enabled = mWifiManager.getVerboseLoggingLevel() > 0;
1460        updateSwitchPreference(mWifiVerboseLogging, enabled);
1461    }
1462
1463    private void writeWifiVerboseLoggingOptions() {
1464        mWifiManager.enableVerboseLogging(mWifiVerboseLogging.isChecked() ? 1 : 0);
1465    }
1466
1467    private void updateWifiAggressiveHandoverOptions() {
1468        boolean enabled = mWifiManager.getAggressiveHandover() > 0;
1469        updateSwitchPreference(mWifiAggressiveHandover, enabled);
1470    }
1471
1472    private void writeWifiAggressiveHandoverOptions() {
1473        mWifiManager.enableAggressiveHandover(mWifiAggressiveHandover.isChecked() ? 1 : 0);
1474    }
1475
1476    private void updateWifiAllowScansWithTrafficOptions() {
1477        boolean enabled = mWifiManager.getAllowScansWithTraffic() > 0;
1478        updateSwitchPreference(mWifiAllowScansWithTraffic, enabled);
1479    }
1480
1481    private void writeWifiAllowScansWithTrafficOptions() {
1482        mWifiManager.setAllowScansWithTraffic(mWifiAllowScansWithTraffic.isChecked() ? 1 : 0);
1483    }
1484
1485    private void updateBluetoothDisableAbsVolumeOptions() {
1486        updateSwitchPreference(mBluetoothDisableAbsVolume,
1487                SystemProperties.getBoolean(BLUETOOTH_DISABLE_ABSOLUTE_VOLUME_PROPERTY, false));
1488    }
1489
1490    private void writeBluetoothDisableAbsVolumeOptions() {
1491        SystemProperties.set(BLUETOOTH_DISABLE_ABSOLUTE_VOLUME_PROPERTY,
1492                mBluetoothDisableAbsVolume.isChecked() ? "true" : "false");
1493    }
1494
1495    private void updateBluetoothEnableInbandRingingOptions() {
1496        if (mBluetoothEnableInbandRinging != null) {
1497            updateSwitchPreference(mBluetoothEnableInbandRinging,
1498                SystemProperties.getBoolean(BLUETOOTH_ENABLE_INBAND_RINGING_PROPERTY, false));
1499        }
1500    }
1501
1502    private void writeBluetoothEnableInbandRingingOptions() {
1503        if (mBluetoothEnableInbandRinging != null) {
1504            SystemProperties.set(BLUETOOTH_ENABLE_INBAND_RINGING_PROPERTY,
1505                mBluetoothEnableInbandRinging.isChecked() ? "true" : "false");
1506        }
1507    }
1508
1509    private void updateMobileDataAlwaysOnOptions() {
1510        updateSwitchPreference(mMobileDataAlwaysOn, Settings.Global.getInt(
1511                getActivity().getContentResolver(),
1512                Settings.Global.MOBILE_DATA_ALWAYS_ON, 1) != 0);
1513    }
1514
1515    private void writeMobileDataAlwaysOnOptions() {
1516        Settings.Global.putInt(getActivity().getContentResolver(),
1517                Settings.Global.MOBILE_DATA_ALWAYS_ON,
1518                mMobileDataAlwaysOn.isChecked() ? 1 : 0);
1519    }
1520
1521    private String defaultLogdSizeValue() {
1522        String defaultValue = SystemProperties.get(SELECT_LOGD_DEFAULT_SIZE_PROPERTY);
1523        if ((defaultValue == null) || (defaultValue.length() == 0)) {
1524            if (SystemProperties.get("ro.config.low_ram").equals("true")) {
1525                defaultValue = SELECT_LOGD_SVELTE_DEFAULT_SIZE_VALUE;
1526            } else {
1527                defaultValue = SELECT_LOGD_DEFAULT_SIZE_VALUE;
1528            }
1529        }
1530        return defaultValue;
1531    }
1532
1533    private void updateLogdSizeValues() {
1534        if (mLogdSize != null) {
1535            String currentTag = SystemProperties.get(SELECT_LOGD_TAG_PROPERTY);
1536            String currentValue = SystemProperties.get(SELECT_LOGD_SIZE_PROPERTY);
1537            if ((currentTag != null) && currentTag.startsWith(SELECT_LOGD_TAG_SILENCE)) {
1538                currentValue = SELECT_LOGD_OFF_SIZE_MARKER_VALUE;
1539            }
1540            if (mLogpersist != null) {
1541                String currentLogpersistEnable
1542                        = SystemProperties.get(ACTUAL_LOGPERSIST_PROPERTY_ENABLE);
1543                if ((currentLogpersistEnable == null)
1544                        || !currentLogpersistEnable.equals("true")
1545                        || currentValue.equals(SELECT_LOGD_OFF_SIZE_MARKER_VALUE)) {
1546                    writeLogpersistOption(null, true);
1547                    mLogpersist.setEnabled(false);
1548                } else if (mSettingsEnabler.getLastEnabledState()) {
1549                    mLogpersist.setEnabled(true);
1550                }
1551            }
1552            if ((currentValue == null) || (currentValue.length() == 0)) {
1553                currentValue = defaultLogdSizeValue();
1554            }
1555            String[] values = getResources().getStringArray(R.array.select_logd_size_values);
1556            String[] titles = getResources().getStringArray(R.array.select_logd_size_titles);
1557            int index = 2; // punt to second entry if not found
1558            if (SystemProperties.get("ro.config.low_ram").equals("true")) {
1559                mLogdSize.setEntries(R.array.select_logd_size_lowram_titles);
1560                titles = getResources().getStringArray(R.array.select_logd_size_lowram_titles);
1561                index = 1;
1562            }
1563            String[] summaries = getResources().getStringArray(R.array.select_logd_size_summaries);
1564            for (int i = 0; i < titles.length; i++) {
1565                if (currentValue.equals(values[i])
1566                        || currentValue.equals(titles[i])) {
1567                    index = i;
1568                    break;
1569                }
1570            }
1571            mLogdSize.setValue(values[index]);
1572            mLogdSize.setSummary(summaries[index]);
1573            mLogdSize.setOnPreferenceChangeListener(this);
1574        }
1575    }
1576
1577    private void writeLogdSizeOption(Object newValue) {
1578        boolean disable = (newValue != null) &&
1579                (newValue.toString().equals(SELECT_LOGD_OFF_SIZE_MARKER_VALUE));
1580        String currentTag = SystemProperties.get(SELECT_LOGD_TAG_PROPERTY);
1581        if (currentTag == null) {
1582            currentTag = "";
1583        }
1584        // filter clean and unstack all references to our setting
1585        String newTag = currentTag.replaceAll(
1586                ",+" + SELECT_LOGD_TAG_SILENCE, "").replaceFirst(
1587                "^" + SELECT_LOGD_TAG_SILENCE + ",*", "").replaceAll(
1588                ",+", ",").replaceFirst(
1589                ",+$", "");
1590        if (disable) {
1591            newValue = SELECT_LOGD_MINIMUM_SIZE_VALUE;
1592            // Make sure snet_event_log get through first, but do not override
1593            String snetValue = SystemProperties.get(SELECT_LOGD_SNET_TAG_PROPERTY);
1594            if ((snetValue == null) || (snetValue.length() == 0)) {
1595                snetValue = SystemProperties.get(SELECT_LOGD_RUNTIME_SNET_TAG_PROPERTY);
1596                if ((snetValue == null) || (snetValue.length() == 0)) {
1597                    SystemProperties.set(SELECT_LOGD_SNET_TAG_PROPERTY, "I");
1598                }
1599            }
1600            // Silence all log sources, security logs notwithstanding
1601            if (newTag.length() != 0) {
1602                newTag = "," + newTag;
1603            }
1604            // Stack settings, stack to help preserve original value
1605            newTag = SELECT_LOGD_TAG_SILENCE + newTag;
1606        }
1607        if (!newTag.equals(currentTag)) {
1608            SystemProperties.set(SELECT_LOGD_TAG_PROPERTY, newTag);
1609        }
1610        String defaultValue = defaultLogdSizeValue();
1611        final String size = ((newValue != null) && (newValue.toString().length() != 0)) ?
1612                newValue.toString() : defaultValue;
1613        SystemProperties.set(SELECT_LOGD_SIZE_PROPERTY, defaultValue.equals(size) ? "" : size);
1614        SystemProperties.set("ctl.start", "logd-reinit");
1615        pokeSystemProperties();
1616        updateLogdSizeValues();
1617    }
1618
1619    private void updateLogpersistValues() {
1620        if (mLogpersist == null) {
1621            return;
1622        }
1623        String currentValue = SystemProperties.get(ACTUAL_LOGPERSIST_PROPERTY);
1624        if (currentValue == null) {
1625            currentValue = "";
1626        }
1627        String currentBuffers = SystemProperties.get(ACTUAL_LOGPERSIST_PROPERTY_BUFFER);
1628        if ((currentBuffers == null) || (currentBuffers.length() == 0)) {
1629            currentBuffers = "all";
1630        }
1631        int index = 0;
1632        if (currentValue.equals(SELECT_LOGPERSIST_PROPERTY_SERVICE)) {
1633            index = 1;
1634            if (currentBuffers.equals("kernel")) {
1635                index = 3;
1636            } else if (!currentBuffers.equals("all") &&
1637                    !currentBuffers.contains("radio") &&
1638                    currentBuffers.contains("security") &&
1639                    currentBuffers.contains("kernel")) {
1640                index = 2;
1641                if (!currentBuffers.contains("default")) {
1642                    String[] contains = {"main", "events", "system", "crash"};
1643                    for (int i = 0; i < contains.length; i++) {
1644                        if (!currentBuffers.contains(contains[i])) {
1645                            index = 1;
1646                            break;
1647                        }
1648                    }
1649                }
1650            }
1651        }
1652        mLogpersist.setValue(
1653                getResources().getStringArray(R.array.select_logpersist_values)[index]);
1654        mLogpersist.setSummary(
1655                getResources().getStringArray(R.array.select_logpersist_summaries)[index]);
1656        mLogpersist.setOnPreferenceChangeListener(this);
1657        if (index != 0) {
1658            mLogpersistCleared = false;
1659        } else if (!mLogpersistCleared) {
1660            // would File.delete() directly but need to switch uid/gid to access
1661            SystemProperties.set(ACTUAL_LOGPERSIST_PROPERTY, SELECT_LOGPERSIST_PROPERTY_CLEAR);
1662            pokeSystemProperties();
1663            mLogpersistCleared = true;
1664        }
1665    }
1666
1667    private void setLogpersistOff(boolean update) {
1668        SystemProperties.set(SELECT_LOGPERSIST_PROPERTY_BUFFER, "");
1669        // deal with trampoline of empty properties
1670        SystemProperties.set(ACTUAL_LOGPERSIST_PROPERTY_BUFFER, "");
1671        SystemProperties.set(SELECT_LOGPERSIST_PROPERTY, "");
1672        SystemProperties.set(ACTUAL_LOGPERSIST_PROPERTY,
1673                update ? "" : SELECT_LOGPERSIST_PROPERTY_STOP);
1674        pokeSystemProperties();
1675        if (update) {
1676            updateLogpersistValues();
1677        } else {
1678            for (int i = 0; i < 3; i++) {
1679                String currentValue = SystemProperties.get(ACTUAL_LOGPERSIST_PROPERTY);
1680                if ((currentValue == null) || currentValue.equals("")) {
1681                    break;
1682                }
1683                try {
1684                    Thread.sleep(100);
1685                } catch (InterruptedException e) {
1686                }
1687            }
1688        }
1689    }
1690
1691    private void writeLogpersistOption(Object newValue, boolean skipWarning) {
1692        if (mLogpersist == null) {
1693            return;
1694        }
1695        String currentTag = SystemProperties.get(SELECT_LOGD_TAG_PROPERTY);
1696        if ((currentTag != null) && currentTag.startsWith(SELECT_LOGD_TAG_SILENCE)) {
1697            newValue = null;
1698            skipWarning = true;
1699        }
1700
1701        if ((newValue == null) || newValue.toString().equals("")) {
1702            if (skipWarning) {
1703                mLogpersistCleared = false;
1704            } else if (!mLogpersistCleared) {
1705                // if transitioning from on to off, pop up an are you sure?
1706                String currentValue = SystemProperties.get(ACTUAL_LOGPERSIST_PROPERTY);
1707                if ((currentValue != null) &&
1708                        currentValue.equals(SELECT_LOGPERSIST_PROPERTY_SERVICE)) {
1709                    if (mLogpersistClearDialog != null) dismissDialogs();
1710                    mLogpersistClearDialog = new AlertDialog.Builder(getActivity()).setMessage(
1711                            getActivity().getResources().getString(
1712                                    R.string.dev_logpersist_clear_warning_message))
1713                            .setTitle(R.string.dev_logpersist_clear_warning_title)
1714                            .setPositiveButton(android.R.string.yes, this)
1715                            .setNegativeButton(android.R.string.no, this)
1716                            .show();
1717                    mLogpersistClearDialog.setOnDismissListener(this);
1718                    return;
1719                }
1720            }
1721            setLogpersistOff(true);
1722            return;
1723        }
1724
1725        String currentBuffer = SystemProperties.get(ACTUAL_LOGPERSIST_PROPERTY_BUFFER);
1726        if ((currentBuffer != null) && !currentBuffer.equals(newValue.toString())) {
1727            setLogpersistOff(false);
1728        }
1729        SystemProperties.set(SELECT_LOGPERSIST_PROPERTY_BUFFER, newValue.toString());
1730        SystemProperties.set(SELECT_LOGPERSIST_PROPERTY, SELECT_LOGPERSIST_PROPERTY_SERVICE);
1731        pokeSystemProperties();
1732        for (int i = 0; i < 3; i++) {
1733            String currentValue = SystemProperties.get(ACTUAL_LOGPERSIST_PROPERTY);
1734            if ((currentValue != null)
1735                    && currentValue.equals(SELECT_LOGPERSIST_PROPERTY_SERVICE)) {
1736                break;
1737            }
1738            try {
1739                Thread.sleep(100);
1740            } catch (InterruptedException e) {
1741            }
1742        }
1743        updateLogpersistValues();
1744    }
1745
1746    private void updateUsbConfigurationValues() {
1747        if (mUsbConfiguration != null) {
1748            UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
1749
1750            String[] values = getResources().getStringArray(R.array.usb_configuration_values);
1751            String[] titles = getResources().getStringArray(R.array.usb_configuration_titles);
1752            int index = 0;
1753            for (int i = 0; i < titles.length; i++) {
1754                if (manager.isFunctionEnabled(values[i])) {
1755                    index = i;
1756                    break;
1757                }
1758            }
1759            mUsbConfiguration.setValue(values[index]);
1760            mUsbConfiguration.setSummary(titles[index]);
1761            mUsbConfiguration.setOnPreferenceChangeListener(this);
1762        }
1763    }
1764
1765    private void writeUsbConfigurationOption(Object newValue) {
1766        UsbManager manager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE);
1767        String function = newValue.toString();
1768        if (function.equals("none")) {
1769            manager.setCurrentFunction(function, false);
1770        } else {
1771            manager.setCurrentFunction(function, true);
1772        }
1773    }
1774
1775    private void initBluetoothConfigurationValues() {
1776        String[] values;
1777        String[] summaries;
1778        int index;
1779
1780        // Init the AVRCP Version - Default
1781        values = getResources().getStringArray(R.array.bluetooth_avrcp_version_values);
1782        summaries = getResources().getStringArray(R.array.bluetooth_avrcp_versions);
1783        String value = SystemProperties.get(BLUETOOTH_AVRCP_VERSION_PROPERTY, values[0]);
1784        index = mBluetoothSelectAvrcpVersion.findIndexOfValue(value);
1785        mBluetoothSelectAvrcpVersion.setValue(values[index]);
1786        mBluetoothSelectAvrcpVersion.setSummary(summaries[index]);
1787
1788        // Init the Codec Type - Default
1789        values = getResources().getStringArray(R.array.bluetooth_a2dp_codec_values);
1790        summaries = getResources().getStringArray(R.array.bluetooth_a2dp_codec_summaries);
1791        index = 0;
1792        mBluetoothSelectA2dpCodec.setValue(values[index]);
1793        mBluetoothSelectA2dpCodec.setSummary(summaries[index]);
1794
1795        // Init the Sample Rate - Default
1796        values = getResources().getStringArray(R.array.bluetooth_a2dp_codec_sample_rate_values);
1797        summaries = getResources().getStringArray(R.array.bluetooth_a2dp_codec_sample_rate_summaries);
1798        index = 0;
1799        mBluetoothSelectA2dpSampleRate.setValue(values[index]);
1800        mBluetoothSelectA2dpSampleRate.setSummary(summaries[index]);
1801
1802        // Init the Bits Per Sample - Default
1803        values = getResources().getStringArray(R.array.bluetooth_a2dp_codec_bits_per_sample_values);
1804        summaries = getResources().getStringArray(R.array.bluetooth_a2dp_codec_bits_per_sample_summaries);
1805        index = 0;
1806        mBluetoothSelectA2dpBitsPerSample.setValue(values[index]);
1807        mBluetoothSelectA2dpBitsPerSample.setSummary(summaries[index]);
1808
1809        // Init the Channel Mode - Default
1810        values = getResources().getStringArray(R.array.bluetooth_a2dp_codec_channel_mode_values);
1811        summaries = getResources().getStringArray(R.array.bluetooth_a2dp_codec_channel_mode_summaries);
1812        index = 0;
1813        mBluetoothSelectA2dpChannelMode.setValue(values[index]);
1814        mBluetoothSelectA2dpChannelMode.setSummary(summaries[index]);
1815
1816        // Init the LDAC Playback Quality - ABR
1817        values = getResources().getStringArray(R.array.bluetooth_a2dp_codec_ldac_playback_quality_values);
1818        summaries = getResources().getStringArray(R.array.bluetooth_a2dp_codec_ldac_playback_quality_summaries);
1819        index = 3;
1820        mBluetoothSelectA2dpLdacPlaybackQuality.setValue(values[index]);
1821        mBluetoothSelectA2dpLdacPlaybackQuality.setSummary(summaries[index]);
1822    }
1823
1824    private void writeBluetoothAvrcpVersion(Object newValue) {
1825        SystemProperties.set(BLUETOOTH_AVRCP_VERSION_PROPERTY, newValue.toString());
1826        int index = mBluetoothSelectAvrcpVersion.findIndexOfValue(newValue.toString());
1827        if (index >= 0) {
1828            String[] titles = getResources().getStringArray(R.array.bluetooth_avrcp_versions);
1829            mBluetoothSelectAvrcpVersion.setSummary(titles[index]);
1830        }
1831    }
1832
1833    private void updateBluetoothA2dpConfigurationValues() {
1834        int index;
1835        String[] summaries;
1836        BluetoothCodecStatus codecStatus = null;
1837        BluetoothCodecConfig codecConfig = null;
1838        BluetoothCodecConfig[] codecsLocalCapabilities = null;
1839        BluetoothCodecConfig[] codecsSelectableCapabilities = null;
1840        String streaming;
1841        Resources resources = null;
1842
1843        synchronized (mBluetoothA2dpLock) {
1844            if (mBluetoothA2dp != null) {
1845                codecStatus = mBluetoothA2dp.getCodecStatus();
1846                if (codecStatus != null) {
1847                    codecConfig = codecStatus.getCodecConfig();
1848                    codecsLocalCapabilities = codecStatus.getCodecsLocalCapabilities();
1849                    codecsSelectableCapabilities = codecStatus.getCodecsSelectableCapabilities();
1850                }
1851            }
1852        }
1853        if (codecConfig == null) {
1854            return;
1855        }
1856
1857        try {
1858            resources = getResources();
1859        } catch (IllegalStateException e) {
1860            return;
1861        }
1862        if (resources == null) {
1863            return;
1864        }
1865
1866        // Update the Codec Type
1867        index = -1;
1868        switch (codecConfig.getCodecType()) {
1869        case BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC:
1870            index = 1;
1871            break;
1872        case BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC:
1873            index = 2;
1874            break;
1875        case BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX:
1876            index = 3;
1877            break;
1878        case BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD:
1879            index = 4;
1880            break;
1881        case BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC:
1882            index = 5;
1883            break;
1884        case BluetoothCodecConfig.SOURCE_CODEC_TYPE_INVALID:
1885        default:
1886            break;
1887        }
1888        if (index >= 0 && mBluetoothSelectA2dpCodec != null) {
1889            summaries = resources.getStringArray(R.array.bluetooth_a2dp_codec_summaries);
1890            streaming = resources.getString(R.string.bluetooth_select_a2dp_codec_streaming_label, summaries[index]);
1891            mBluetoothSelectA2dpCodec.setSummary(streaming);
1892        }
1893
1894        // Update the Sample Rate
1895        index = -1;
1896        switch (codecConfig.getSampleRate()) {
1897        case BluetoothCodecConfig.SAMPLE_RATE_44100:
1898            index = 1;
1899            break;
1900        case BluetoothCodecConfig.SAMPLE_RATE_48000:
1901            index = 2;
1902            break;
1903        case BluetoothCodecConfig.SAMPLE_RATE_88200:
1904            index = 3;
1905            break;
1906        case BluetoothCodecConfig.SAMPLE_RATE_96000:
1907            index = 4;
1908            break;
1909        case BluetoothCodecConfig.SAMPLE_RATE_176400:
1910        case BluetoothCodecConfig.SAMPLE_RATE_192000:
1911        case BluetoothCodecConfig.SAMPLE_RATE_NONE:
1912        default:
1913            break;
1914        }
1915        if (index >= 0 && mBluetoothSelectA2dpSampleRate != null) {
1916            summaries = resources.getStringArray(R.array.bluetooth_a2dp_codec_sample_rate_summaries);
1917            streaming = resources.getString(R.string.bluetooth_select_a2dp_codec_streaming_label, summaries[index]);
1918             mBluetoothSelectA2dpSampleRate.setSummary(streaming);
1919        }
1920
1921        // Update the Bits Per Sample
1922        index = -1;
1923        switch (codecConfig.getBitsPerSample()) {
1924        case BluetoothCodecConfig.BITS_PER_SAMPLE_16:
1925            index = 1;
1926            break;
1927        case BluetoothCodecConfig.BITS_PER_SAMPLE_24:
1928            index = 2;
1929            break;
1930        case BluetoothCodecConfig.BITS_PER_SAMPLE_32:
1931            index = 3;
1932            break;
1933        case BluetoothCodecConfig.BITS_PER_SAMPLE_NONE:
1934        default:
1935            break;
1936        }
1937        if (index >= 0 && mBluetoothSelectA2dpBitsPerSample != null) {
1938            summaries = resources.getStringArray(R.array.bluetooth_a2dp_codec_bits_per_sample_summaries);
1939            streaming = resources.getString(R.string.bluetooth_select_a2dp_codec_streaming_label, summaries[index]);
1940            mBluetoothSelectA2dpBitsPerSample.setSummary(streaming);
1941        }
1942
1943        // Update the Channel Mode
1944        index = -1;
1945        switch (codecConfig.getChannelMode()) {
1946        case BluetoothCodecConfig.CHANNEL_MODE_MONO:
1947            index = 1;
1948            break;
1949        case BluetoothCodecConfig.CHANNEL_MODE_STEREO:
1950            index = 2;
1951            break;
1952        case BluetoothCodecConfig.CHANNEL_MODE_NONE:
1953        default:
1954            break;
1955        }
1956        if (index >= 0 && mBluetoothSelectA2dpChannelMode != null) {
1957            summaries = resources.getStringArray(R.array.bluetooth_a2dp_codec_channel_mode_summaries);
1958            streaming = resources.getString(R.string.bluetooth_select_a2dp_codec_streaming_label, summaries[index]);
1959             mBluetoothSelectA2dpChannelMode.setSummary(streaming);
1960        }
1961
1962        // Update the LDAC Playback Quality
1963        // The actual values are 0, 1, 2 - those are extracted
1964        // as mod-10 remainders of a larger value.
1965        // The reason is because within BluetoothCodecConfig we cannot use
1966        // a codec-specific value of zero.
1967        index = (int)codecConfig.getCodecSpecific1();
1968        if (index > 0) {
1969            index %= 10;
1970        } else {
1971            index = -1;
1972        }
1973        switch (index) {
1974        case 0:
1975        case 1:
1976        case 2:
1977        case 3:
1978            break;
1979        default:
1980            index = -1;
1981            break;
1982        }
1983        if (index >= 0 && mBluetoothSelectA2dpLdacPlaybackQuality != null) {
1984            summaries = resources.getStringArray(R.array.bluetooth_a2dp_codec_ldac_playback_quality_summaries);
1985            streaming = resources.getString(R.string.bluetooth_select_a2dp_codec_streaming_label, summaries[index]);
1986            mBluetoothSelectA2dpLdacPlaybackQuality.setSummary(streaming);
1987        }
1988    }
1989
1990    private void writeBluetoothConfigurationOption(Preference preference,
1991                                                   Object newValue) {
1992        String[] summaries;
1993        int index;
1994        int codecTypeValue = BluetoothCodecConfig.SOURCE_CODEC_TYPE_INVALID;
1995        int codecPriorityValue = BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT;
1996        int sampleRateValue = BluetoothCodecConfig.SAMPLE_RATE_NONE;
1997        int bitsPerSampleValue = BluetoothCodecConfig.BITS_PER_SAMPLE_NONE;
1998        int channelModeValue = BluetoothCodecConfig.CHANNEL_MODE_NONE;
1999        long codecSpecific1Value = 0;
2000        long codecSpecific2Value = 0;
2001        long codecSpecific3Value = 0;
2002        long codecSpecific4Value = 0;
2003
2004        // Codec Type
2005        String codecType = mBluetoothSelectA2dpCodec.getValue();
2006        if (preference == mBluetoothSelectA2dpCodec) {
2007            codecType = newValue.toString();
2008            index = mBluetoothSelectA2dpCodec.findIndexOfValue(newValue.toString());
2009            if (index >= 0) {
2010                summaries = getResources().getStringArray(R.array.bluetooth_a2dp_codec_summaries);
2011                mBluetoothSelectA2dpCodec.setSummary(summaries[index]);
2012            }
2013        }
2014        index = mBluetoothSelectA2dpCodec.findIndexOfValue(codecType);
2015        switch (index) {
2016        case 0:
2017            // Reset the priority of the current codec to default
2018            String oldValue = mBluetoothSelectA2dpCodec.getValue();
2019            switch (mBluetoothSelectA2dpCodec.findIndexOfValue(oldValue)) {
2020            case 0:
2021                break;      // No current codec
2022            case 1:
2023                codecTypeValue = BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC;
2024                break;
2025            case 2:
2026                codecTypeValue = BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC;
2027                break;
2028            case 3:
2029                codecTypeValue = BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX;
2030                break;
2031            case 4:
2032                codecTypeValue = BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD;
2033                break;
2034            case 5:
2035                codecTypeValue = BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC;
2036                break;
2037            default:
2038                break;
2039            }
2040            break;
2041        case 1:
2042            codecTypeValue = BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC;
2043            codecPriorityValue = BluetoothCodecConfig.CODEC_PRIORITY_HIGHEST;
2044            break;
2045        case 2:
2046            codecTypeValue = BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC;
2047            codecPriorityValue = BluetoothCodecConfig.CODEC_PRIORITY_HIGHEST;
2048            break;
2049        case 3:
2050            codecTypeValue = BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX;
2051            codecPriorityValue = BluetoothCodecConfig.CODEC_PRIORITY_HIGHEST;
2052            break;
2053        case 4:
2054            codecTypeValue = BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD;
2055            codecPriorityValue = BluetoothCodecConfig.CODEC_PRIORITY_HIGHEST;
2056            break;
2057        case 5:
2058            codecTypeValue = BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC;
2059            codecPriorityValue = BluetoothCodecConfig.CODEC_PRIORITY_HIGHEST;
2060            break;
2061        case 6:
2062        synchronized (mBluetoothA2dpLock) {
2063            if (mBluetoothA2dp != null) {
2064                mBluetoothA2dp.enableOptionalCodecs();
2065            }
2066        }
2067        return;
2068        case 7:
2069        synchronized (mBluetoothA2dpLock) {
2070            if (mBluetoothA2dp != null) {
2071                mBluetoothA2dp.disableOptionalCodecs();
2072            }
2073        }
2074        return;
2075        default:
2076            break;
2077        }
2078
2079        // Sample Rate
2080        String sampleRate = mBluetoothSelectA2dpSampleRate.getValue();
2081        if (preference == mBluetoothSelectA2dpSampleRate) {
2082            sampleRate = newValue.toString();
2083            index = mBluetoothSelectA2dpSampleRate.findIndexOfValue(newValue.toString());
2084            if (index >= 0) {
2085                summaries = getResources().getStringArray(R.array.bluetooth_a2dp_codec_sample_rate_summaries);
2086                mBluetoothSelectA2dpSampleRate.setSummary(summaries[index]);
2087            }
2088        }
2089        index = mBluetoothSelectA2dpSampleRate.findIndexOfValue(sampleRate);
2090        switch (index) {
2091        case 0:
2092            // Reset to default
2093            break;
2094        case 1:
2095            sampleRateValue = BluetoothCodecConfig.SAMPLE_RATE_44100;
2096            break;
2097        case 2:
2098            sampleRateValue = BluetoothCodecConfig.SAMPLE_RATE_48000;
2099            break;
2100        case 3:
2101            sampleRateValue = BluetoothCodecConfig.SAMPLE_RATE_88200;
2102            break;
2103        case 4:
2104            sampleRateValue = BluetoothCodecConfig.SAMPLE_RATE_96000;
2105            break;
2106        default:
2107            break;
2108        }
2109
2110        // Bits Per Sample
2111        String bitsPerSample = mBluetoothSelectA2dpBitsPerSample.getValue();
2112        if (preference == mBluetoothSelectA2dpBitsPerSample) {
2113            bitsPerSample = newValue.toString();
2114            index = mBluetoothSelectA2dpBitsPerSample.findIndexOfValue(newValue.toString());
2115            if (index >= 0) {
2116                summaries = getResources().getStringArray(R.array.bluetooth_a2dp_codec_bits_per_sample_summaries);
2117                mBluetoothSelectA2dpBitsPerSample.setSummary(summaries[index]);
2118            }
2119        }
2120        index = mBluetoothSelectA2dpBitsPerSample.findIndexOfValue(bitsPerSample);
2121        switch (index) {
2122        case 0:
2123            // Reset to default
2124            break;
2125        case 1:
2126            bitsPerSampleValue = BluetoothCodecConfig.BITS_PER_SAMPLE_16;
2127            break;
2128        case 2:
2129            bitsPerSampleValue = BluetoothCodecConfig.BITS_PER_SAMPLE_24;
2130            break;
2131        case 3:
2132            bitsPerSampleValue = BluetoothCodecConfig.BITS_PER_SAMPLE_32;
2133            break;
2134        default:
2135            break;
2136        }
2137
2138        // Channel Mode
2139        String channelMode = mBluetoothSelectA2dpChannelMode.getValue();
2140        if (preference == mBluetoothSelectA2dpChannelMode) {
2141            channelMode = newValue.toString();
2142            index = mBluetoothSelectA2dpChannelMode.findIndexOfValue(newValue.toString());
2143            if (index >= 0) {
2144                summaries = getResources().getStringArray(R.array.bluetooth_a2dp_codec_channel_mode_summaries);
2145                mBluetoothSelectA2dpChannelMode.setSummary(summaries[index]);
2146            }
2147        }
2148        index = mBluetoothSelectA2dpChannelMode.findIndexOfValue(channelMode);
2149        switch (index) {
2150        case 0:
2151            // Reset to default
2152            break;
2153        case 1:
2154            channelModeValue = BluetoothCodecConfig.CHANNEL_MODE_MONO;
2155            break;
2156        case 2:
2157            channelModeValue = BluetoothCodecConfig.CHANNEL_MODE_STEREO;
2158            break;
2159        default:
2160            break;
2161        }
2162
2163        // LDAC Playback Quality
2164        String ldacPlaybackQuality = mBluetoothSelectA2dpLdacPlaybackQuality.getValue();
2165        if (preference == mBluetoothSelectA2dpLdacPlaybackQuality) {
2166            ldacPlaybackQuality = newValue.toString();
2167            index = mBluetoothSelectA2dpLdacPlaybackQuality.findIndexOfValue(newValue.toString());
2168            if (index >= 0) {
2169                summaries = getResources().getStringArray(R.array.bluetooth_a2dp_codec_ldac_playback_quality_summaries);
2170                mBluetoothSelectA2dpLdacPlaybackQuality.setSummary(summaries[index]);
2171            }
2172        }
2173        index = mBluetoothSelectA2dpLdacPlaybackQuality.findIndexOfValue(ldacPlaybackQuality);
2174        switch (index) {
2175        case 0:
2176        case 1:
2177        case 2:
2178        case 3:
2179            codecSpecific1Value = 1000 + index;
2180            break;
2181        default:
2182            break;
2183        }
2184
2185        BluetoothCodecConfig codecConfig =
2186            new BluetoothCodecConfig(codecTypeValue, codecPriorityValue,
2187                                     sampleRateValue, bitsPerSampleValue,
2188                                     channelModeValue, codecSpecific1Value,
2189                                     codecSpecific2Value, codecSpecific3Value,
2190                                     codecSpecific4Value);
2191
2192        synchronized (mBluetoothA2dpLock) {
2193            if (mBluetoothA2dp != null) {
2194                mBluetoothA2dp.setCodecConfigPreference(codecConfig);
2195            }
2196        }
2197    }
2198
2199    private void writeImmediatelyDestroyActivitiesOptions() {
2200        try {
2201            ActivityManager.getService().setAlwaysFinish(
2202                    mImmediatelyDestroyActivities.isChecked());
2203        } catch (RemoteException ex) {
2204        }
2205    }
2206
2207    private void updateImmediatelyDestroyActivitiesOptions() {
2208        updateSwitchPreference(mImmediatelyDestroyActivities, Settings.Global.getInt(
2209                getActivity().getContentResolver(), Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0)
2210                != 0);
2211    }
2212
2213    private void updateAnimationScaleValue(int which, ListPreference pref) {
2214        try {
2215            float scale = mWindowManager.getAnimationScale(which);
2216            if (scale != 1) {
2217                mHaveDebugSettings = true;
2218            }
2219            CharSequence[] values = pref.getEntryValues();
2220            for (int i = 0; i < values.length; i++) {
2221                float val = Float.parseFloat(values[i].toString());
2222                if (scale <= val) {
2223                    pref.setValueIndex(i);
2224                    pref.setSummary(pref.getEntries()[i]);
2225                    return;
2226                }
2227            }
2228            pref.setValueIndex(values.length - 1);
2229            pref.setSummary(pref.getEntries()[0]);
2230        } catch (RemoteException e) {
2231        }
2232    }
2233
2234    private void updateAnimationScaleOptions() {
2235        updateAnimationScaleValue(0, mWindowAnimationScale);
2236        updateAnimationScaleValue(1, mTransitionAnimationScale);
2237        updateAnimationScaleValue(2, mAnimatorDurationScale);
2238    }
2239
2240    private void writeAnimationScaleOption(int which, ListPreference pref, Object newValue) {
2241        try {
2242            float scale = newValue != null ? Float.parseFloat(newValue.toString()) : 1;
2243            mWindowManager.setAnimationScale(which, scale);
2244            updateAnimationScaleValue(which, pref);
2245        } catch (RemoteException e) {
2246        }
2247    }
2248
2249    private void updateOverlayDisplayDevicesOptions() {
2250        String value = Settings.Global.getString(getActivity().getContentResolver(),
2251                Settings.Global.OVERLAY_DISPLAY_DEVICES);
2252        if (value == null) {
2253            value = "";
2254        }
2255
2256        CharSequence[] values = mOverlayDisplayDevices.getEntryValues();
2257        for (int i = 0; i < values.length; i++) {
2258            if (value.contentEquals(values[i])) {
2259                mOverlayDisplayDevices.setValueIndex(i);
2260                mOverlayDisplayDevices.setSummary(mOverlayDisplayDevices.getEntries()[i]);
2261                return;
2262            }
2263        }
2264        mOverlayDisplayDevices.setValueIndex(0);
2265        mOverlayDisplayDevices.setSummary(mOverlayDisplayDevices.getEntries()[0]);
2266    }
2267
2268    private void writeOverlayDisplayDevicesOptions(Object newValue) {
2269        Settings.Global.putString(getActivity().getContentResolver(),
2270                Settings.Global.OVERLAY_DISPLAY_DEVICES, (String) newValue);
2271        updateOverlayDisplayDevicesOptions();
2272    }
2273
2274    private void updateAppProcessLimitOptions() {
2275        try {
2276            int limit = ActivityManager.getService().getProcessLimit();
2277            CharSequence[] values = mAppProcessLimit.getEntryValues();
2278            for (int i = 0; i < values.length; i++) {
2279                int val = Integer.parseInt(values[i].toString());
2280                if (val >= limit) {
2281                    if (i != 0) {
2282                        mHaveDebugSettings = true;
2283                    }
2284                    mAppProcessLimit.setValueIndex(i);
2285                    mAppProcessLimit.setSummary(mAppProcessLimit.getEntries()[i]);
2286                    return;
2287                }
2288            }
2289            mAppProcessLimit.setValueIndex(0);
2290            mAppProcessLimit.setSummary(mAppProcessLimit.getEntries()[0]);
2291        } catch (RemoteException e) {
2292        }
2293    }
2294
2295    private void writeAppProcessLimitOptions(Object newValue) {
2296        try {
2297            int limit = newValue != null ? Integer.parseInt(newValue.toString()) : -1;
2298            ActivityManager.getService().setProcessLimit(limit);
2299            updateAppProcessLimitOptions();
2300        } catch (RemoteException e) {
2301        }
2302    }
2303
2304    private void writeShowAllANRsOptions() {
2305        Settings.Secure.putInt(getActivity().getContentResolver(),
2306                Settings.Secure.ANR_SHOW_BACKGROUND,
2307                mShowAllANRs.isChecked() ? 1 : 0);
2308    }
2309
2310    private void updateShowAllANRsOptions() {
2311        updateSwitchPreference(mShowAllANRs, Settings.Secure.getInt(
2312                getActivity().getContentResolver(), Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0);
2313    }
2314
2315    private void confirmEnableOemUnlock() {
2316        DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {
2317            @Override
2318            public void onClick(DialogInterface dialog, int which) {
2319                if (which == DialogInterface.BUTTON_POSITIVE) {
2320                    mOemLockManager.setOemUnlockAllowedByUser(true);
2321                }
2322            }
2323        };
2324
2325        DialogInterface.OnDismissListener onDismissListener =
2326                new DialogInterface.OnDismissListener() {
2327                    @Override
2328                    public void onDismiss(DialogInterface dialog) {
2329                        if (getActivity() == null) {
2330                            return;
2331                        }
2332                        updateAllOptions();
2333                    }
2334                };
2335
2336        new AlertDialog.Builder(getActivity())
2337                .setTitle(R.string.confirm_enable_oem_unlock_title)
2338                .setMessage(R.string.confirm_enable_oem_unlock_text)
2339                .setPositiveButton(R.string.enable_text, onClickListener)
2340                .setNegativeButton(android.R.string.cancel, null)
2341                .setOnDismissListener(onDismissListener)
2342                .create()
2343                .show();
2344    }
2345
2346    @Override
2347    public void onSwitchChanged(Switch switchView, boolean isChecked) {
2348        if (switchView != mSwitchBar.getSwitch()) {
2349            return;
2350        }
2351        final boolean lastEnabledState = mSettingsEnabler.getLastEnabledState();
2352        if (isChecked != lastEnabledState) {
2353            if (isChecked) {
2354                mDialogClicked = false;
2355                if (mEnableDialog != null) dismissDialogs();
2356                mEnableDialog = new AlertDialog.Builder(getActivity()).setMessage(
2357                        getActivity().getResources().getString(
2358                                R.string.dev_settings_warning_message))
2359                        .setTitle(R.string.dev_settings_warning_title)
2360                        .setPositiveButton(android.R.string.yes, this)
2361                        .setNegativeButton(android.R.string.no, this)
2362                        .show();
2363                mEnableDialog.setOnDismissListener(this);
2364            } else {
2365                resetDangerousOptions();
2366                mSettingsEnabler.disableDevelopmentSettings();
2367                setPrefsEnabledState(false);
2368            }
2369        }
2370    }
2371
2372    @Override
2373    public void onActivityResult(int requestCode, int resultCode, Intent data) {
2374        if (requestCode == RESULT_DEBUG_APP) {
2375            if (resultCode == Activity.RESULT_OK) {
2376                mDebugApp = data.getAction();
2377                writeDebuggerOptions();
2378                updateDebuggerOptions();
2379            }
2380        } else if (requestCode == RESULT_MOCK_LOCATION_APP) {
2381            if (resultCode == Activity.RESULT_OK) {
2382                mMockLocationApp = data.getAction();
2383                writeMockLocation();
2384                updateMockLocation();
2385            }
2386        } else if (requestCode == REQUEST_CODE_ENABLE_OEM_UNLOCK) {
2387            if (resultCode == Activity.RESULT_OK) {
2388                if (mEnableOemUnlock.isChecked()) {
2389                    confirmEnableOemUnlock();
2390                } else {
2391                    mOemLockManager.setOemUnlockAllowedByUser(false);
2392                }
2393            }
2394        } else {
2395            super.onActivityResult(requestCode, resultCode, data);
2396        }
2397    }
2398
2399    @Override
2400    public boolean onPreferenceTreeClick(Preference preference) {
2401        if (Utils.isMonkeyRunning()) {
2402            return false;
2403        }
2404
2405        if (mBugReportInPowerController.handlePreferenceTreeClick(preference)) {
2406            return true;
2407        }
2408
2409        if (mTelephonyMonitorController.handlePreferenceTreeClick(preference)) {
2410            return true;
2411        }
2412
2413        if (mWebViewAppPrefController.handlePreferenceTreeClick(preference)) {
2414            return true;
2415        }
2416
2417        if (preference == mEnableAdb) {
2418            if (mEnableAdb.isChecked()) {
2419                mDialogClicked = false;
2420                if (mAdbDialog != null) dismissDialogs();
2421                mAdbDialog = new AlertDialog.Builder(getActivity()).setMessage(
2422                        getActivity().getResources().getString(R.string.adb_warning_message))
2423                        .setTitle(R.string.adb_warning_title)
2424                        .setPositiveButton(android.R.string.yes, this)
2425                        .setNegativeButton(android.R.string.no, this)
2426                        .show();
2427                mAdbDialog.setOnDismissListener(this);
2428            } else {
2429                Settings.Global.putInt(getActivity().getContentResolver(),
2430                        Settings.Global.ADB_ENABLED, 0);
2431                mVerifyAppsOverUsb.setEnabled(false);
2432                mVerifyAppsOverUsb.setChecked(false);
2433                updateBugreportOptions();
2434            }
2435        } else if (preference == mClearAdbKeys) {
2436            if (mAdbKeysDialog != null) dismissDialogs();
2437            mAdbKeysDialog = new AlertDialog.Builder(getActivity())
2438                    .setMessage(R.string.adb_keys_warning_message)
2439                    .setPositiveButton(android.R.string.ok, this)
2440                    .setNegativeButton(android.R.string.cancel, null)
2441                    .show();
2442        } else if (preference == mEnableTerminal) {
2443            final PackageManager pm = getActivity().getPackageManager();
2444            pm.setApplicationEnabledSetting(TERMINAL_APP_PACKAGE,
2445                    mEnableTerminal.isChecked() ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
2446                            : PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0);
2447        } else if (preference == mKeepScreenOn) {
2448            Settings.Global.putInt(getActivity().getContentResolver(),
2449                    Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
2450                    mKeepScreenOn.isChecked() ?
2451                            (BatteryManager.BATTERY_PLUGGED_AC | BatteryManager.BATTERY_PLUGGED_USB
2452                                    | BatteryManager.BATTERY_PLUGGED_WIRELESS) : 0);
2453        } else if (preference == mBtHciSnoopLog) {
2454            writeBtHciSnoopLogOptions();
2455        } else if (preference == mEnableOemUnlock && mEnableOemUnlock.isEnabled()) {
2456            if (mEnableOemUnlock.isChecked()) {
2457                if (!showKeyguardConfirmation(getResources(), REQUEST_CODE_ENABLE_OEM_UNLOCK)) {
2458                    confirmEnableOemUnlock();
2459                }
2460            } else {
2461                mOemLockManager.setOemUnlockAllowedByUser(false);
2462            }
2463        } else if (preference == mMockLocationAppPref) {
2464            Intent intent = new Intent(getActivity(), AppPicker.class);
2465            intent.putExtra(AppPicker.EXTRA_REQUESTIING_PERMISSION,
2466                    Manifest.permission.ACCESS_MOCK_LOCATION);
2467            startActivityForResult(intent, RESULT_MOCK_LOCATION_APP);
2468        } else if (preference == mDebugViewAttributes) {
2469            Settings.Global.putInt(getActivity().getContentResolver(),
2470                    Settings.Global.DEBUG_VIEW_ATTRIBUTES,
2471                    mDebugViewAttributes.isChecked() ? 1 : 0);
2472        } else if (preference == mForceAllowOnExternal) {
2473            Settings.Global.putInt(getActivity().getContentResolver(),
2474                    Settings.Global.FORCE_ALLOW_ON_EXTERNAL,
2475                    mForceAllowOnExternal.isChecked() ? 1 : 0);
2476        } else if (preference == mDebugAppPref) {
2477            Intent intent = new Intent(getActivity(), AppPicker.class);
2478            intent.putExtra(AppPicker.EXTRA_DEBUGGABLE, true);
2479            startActivityForResult(intent, RESULT_DEBUG_APP);
2480        } else if (preference == mWaitForDebugger) {
2481            writeDebuggerOptions();
2482        } else if (preference == mVerifyAppsOverUsb) {
2483            writeVerifyAppsOverUsbOptions();
2484        } else if (preference == mOtaDisableAutomaticUpdate) {
2485            writeOtaDisableAutomaticUpdateOptions();
2486        } else if (preference == mStrictMode) {
2487            writeStrictModeVisualOptions();
2488        } else if (preference == mPointerLocation) {
2489            writePointerLocationOptions();
2490        } else if (preference == mShowTouches) {
2491            writeShowTouchesOptions();
2492        } else if (preference == mShowScreenUpdates) {
2493            writeShowUpdatesOption();
2494        } else if (preference == mDisableOverlays) {
2495            writeDisableOverlaysOption();
2496        } else if (preference == mImmediatelyDestroyActivities) {
2497            writeImmediatelyDestroyActivitiesOptions();
2498        } else if (preference == mShowAllANRs) {
2499            writeShowAllANRsOptions();
2500        } else if (preference == mForceHardwareUi) {
2501            writeHardwareUiOptions();
2502        } else if (preference == mForceMsaa) {
2503            writeMsaaOptions();
2504        } else if (preference == mShowHwScreenUpdates) {
2505            writeShowHwScreenUpdatesOptions();
2506        } else if (preference == mShowHwLayersUpdates) {
2507            writeShowHwLayersUpdatesOptions();
2508        } else if (preference == mDebugLayout) {
2509            writeDebugLayoutOptions();
2510        } else if (preference == mForceRtlLayout) {
2511            writeForceRtlOptions();
2512        } else if (preference == mWifiDisplayCertification) {
2513            writeWifiDisplayCertificationOptions();
2514        } else if (preference == mWifiVerboseLogging) {
2515            writeWifiVerboseLoggingOptions();
2516        } else if (preference == mWifiAggressiveHandover) {
2517            writeWifiAggressiveHandoverOptions();
2518        } else if (preference == mWifiAllowScansWithTraffic) {
2519            writeWifiAllowScansWithTrafficOptions();
2520        } else if (preference == mMobileDataAlwaysOn) {
2521            writeMobileDataAlwaysOnOptions();
2522        } else if (preference == mColorTemperaturePreference) {
2523            writeColorTemperature();
2524        } else if (preference == mUSBAudio) {
2525            writeUSBAudioOptions();
2526        } else if (preference == mForceResizable) {
2527            writeForceResizableOptions();
2528        } else if (preference == mBluetoothDisableAbsVolume) {
2529            writeBluetoothDisableAbsVolumeOptions();
2530        } else if (preference == mBluetoothEnableInbandRinging) {
2531            writeBluetoothEnableInbandRingingOptions();
2532        } else if (SHORTCUT_MANAGER_RESET_KEY.equals(preference.getKey())) {
2533            resetShortcutManagerThrottling();
2534        } else {
2535            return super.onPreferenceTreeClick(preference);
2536        }
2537
2538        return false;
2539    }
2540
2541    private boolean showKeyguardConfirmation(Resources resources, int requestCode) {
2542        return new ChooseLockSettingsHelper(getActivity(), this).launchConfirmationActivity(
2543                requestCode, resources.getString(R.string.oem_unlock_enable));
2544    }
2545
2546    @Override
2547    public boolean onPreferenceChange(Preference preference, Object newValue) {
2548        if (HDCP_CHECKING_KEY.equals(preference.getKey())) {
2549            SystemProperties.set(HDCP_CHECKING_PROPERTY, newValue.toString());
2550            updateHdcpValues();
2551            pokeSystemProperties();
2552            return true;
2553        } else if (preference == mBluetoothSelectAvrcpVersion) {
2554           writeBluetoothAvrcpVersion(newValue);
2555           return true;
2556        } else if ((preference == mBluetoothSelectA2dpCodec) ||
2557                   (preference == mBluetoothSelectA2dpSampleRate) ||
2558                   (preference == mBluetoothSelectA2dpBitsPerSample) ||
2559                   (preference == mBluetoothSelectA2dpChannelMode) ||
2560                   (preference == mBluetoothSelectA2dpLdacPlaybackQuality)) {
2561            writeBluetoothConfigurationOption(preference, newValue);
2562            return true;
2563        } else if (preference == mLogdSize) {
2564            writeLogdSizeOption(newValue);
2565            return true;
2566        } else if (preference == mLogpersist) {
2567            writeLogpersistOption(newValue, false);
2568            return true;
2569        } else if (preference == mUsbConfiguration) {
2570            writeUsbConfigurationOption(newValue);
2571            return true;
2572        } else if (preference == mWindowAnimationScale) {
2573            writeAnimationScaleOption(0, mWindowAnimationScale, newValue);
2574            return true;
2575        } else if (preference == mTransitionAnimationScale) {
2576            writeAnimationScaleOption(1, mTransitionAnimationScale, newValue);
2577            return true;
2578        } else if (preference == mAnimatorDurationScale) {
2579            writeAnimationScaleOption(2, mAnimatorDurationScale, newValue);
2580            return true;
2581        } else if (preference == mOverlayDisplayDevices) {
2582            writeOverlayDisplayDevicesOptions(newValue);
2583            return true;
2584        } else if (preference == mTrackFrameTime) {
2585            writeTrackFrameTimeOptions(newValue);
2586            return true;
2587        } else if (preference == mDebugHwOverdraw) {
2588            writeDebugHwOverdrawOptions(newValue);
2589            return true;
2590        } else if (preference == mDebugHwRenderer) {
2591            writeDebugHwRendererOptions(newValue);
2592            return true;
2593        } else if (preference == mShowNonRectClip) {
2594            writeShowNonRectClipOptions(newValue);
2595            return true;
2596        } else if (preference == mAppProcessLimit) {
2597            writeAppProcessLimitOptions(newValue);
2598            return true;
2599        } else if (preference == mSimulateColorSpace) {
2600            writeSimulateColorSpace(newValue);
2601            return true;
2602        }
2603        return false;
2604    }
2605
2606    private void dismissDialogs() {
2607        if (mAdbDialog != null) {
2608            mAdbDialog.dismiss();
2609            mAdbDialog = null;
2610        }
2611        if (mAdbKeysDialog != null) {
2612            mAdbKeysDialog.dismiss();
2613            mAdbKeysDialog = null;
2614        }
2615        if (mEnableDialog != null) {
2616            mEnableDialog.dismiss();
2617            mEnableDialog = null;
2618        }
2619        if (mLogpersistClearDialog != null) {
2620            mLogpersistClearDialog.dismiss();
2621            mLogpersistClearDialog = null;
2622        }
2623    }
2624
2625    public void onClick(DialogInterface dialog, int which) {
2626        if (dialog == mAdbDialog) {
2627            if (which == DialogInterface.BUTTON_POSITIVE) {
2628                mDialogClicked = true;
2629                Settings.Global.putInt(getActivity().getContentResolver(),
2630                        Settings.Global.ADB_ENABLED, 1);
2631                mVerifyAppsOverUsb.setEnabled(true);
2632                updateVerifyAppsOverUsbOptions();
2633                updateBugreportOptions();
2634            } else {
2635                // Reset the toggle
2636                mEnableAdb.setChecked(false);
2637            }
2638        } else if (dialog == mAdbKeysDialog) {
2639            if (which == DialogInterface.BUTTON_POSITIVE) {
2640                try {
2641                    IBinder b = ServiceManager.getService(Context.USB_SERVICE);
2642                    IUsbManager service = IUsbManager.Stub.asInterface(b);
2643                    service.clearUsbDebuggingKeys();
2644                } catch (RemoteException e) {
2645                    Log.e(TAG, "Unable to clear adb keys", e);
2646                }
2647            }
2648        } else if (dialog == mEnableDialog) {
2649            if (which == DialogInterface.BUTTON_POSITIVE) {
2650                mDialogClicked = true;
2651                mSettingsEnabler.enableDevelopmentSettings();
2652                setPrefsEnabledState(true);
2653            } else {
2654                // Reset the toggle
2655                mSwitchBar.setChecked(false);
2656            }
2657        } else if (dialog == mLogpersistClearDialog) {
2658            if (which == DialogInterface.BUTTON_POSITIVE) {
2659                setLogpersistOff(true);
2660            } else {
2661                updateLogpersistValues();
2662            }
2663        }
2664    }
2665
2666    public void onDismiss(DialogInterface dialog) {
2667        // Assuming that onClick gets called first
2668        if (dialog == mAdbDialog) {
2669            if (!mDialogClicked) {
2670                mEnableAdb.setChecked(false);
2671            }
2672            mAdbDialog = null;
2673        } else if (dialog == mEnableDialog) {
2674            if (!mDialogClicked) {
2675                mSwitchBar.setChecked(false);
2676            }
2677            mEnableDialog = null;
2678        } else if (dialog == mLogpersistClearDialog) {
2679            mLogpersistClearDialog = null;
2680        }
2681    }
2682
2683    @Override
2684    public void onDestroy() {
2685        dismissDialogs();
2686        super.onDestroy();
2687    }
2688
2689    void pokeSystemProperties() {
2690        if (!mDontPokeProperties) {
2691            //noinspection unchecked
2692            (new SystemPropPoker()).execute();
2693        }
2694    }
2695
2696    private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
2697        @Override
2698        public void onReceive(Context context, Intent intent) {
2699            updateUsbConfigurationValues();
2700        }
2701    };
2702
2703    private BroadcastReceiver mBluetoothA2dpReceiver = new BroadcastReceiver() {
2704        @Override
2705        public void onReceive(Context context, Intent intent) {
2706            Log.d(TAG, "mBluetoothA2dpReceiver.onReceive intent=" + intent);
2707            String action = intent.getAction();
2708
2709            if (BluetoothA2dp.ACTION_CODEC_CONFIG_CHANGED.equals(action)) {
2710                BluetoothCodecStatus codecStatus =
2711                    (BluetoothCodecStatus)intent.getParcelableExtra(BluetoothCodecStatus.EXTRA_CODEC_STATUS);
2712                Log.d(TAG, "Received BluetoothCodecStatus=" + codecStatus);
2713                updateBluetoothA2dpConfigurationValues();
2714            }
2715        }
2716    };
2717
2718    private BluetoothProfile.ServiceListener mBluetoothA2dpServiceListener =
2719        new BluetoothProfile.ServiceListener() {
2720            public void onServiceConnected(int profile,
2721                                           BluetoothProfile proxy) {
2722                synchronized (mBluetoothA2dpLock) {
2723                    mBluetoothA2dp = (BluetoothA2dp) proxy;
2724                }
2725                updateBluetoothA2dpConfigurationValues();
2726            }
2727
2728            public void onServiceDisconnected(int profile) {
2729                synchronized (mBluetoothA2dpLock) {
2730                    mBluetoothA2dp = null;
2731                }
2732                updateBluetoothA2dpConfigurationValues();
2733            }
2734        };
2735
2736    public static class SystemPropPoker extends AsyncTask<Void, Void, Void> {
2737        @Override
2738        protected Void doInBackground(Void... params) {
2739            String[] services = ServiceManager.listServices();
2740            for (String service : services) {
2741                IBinder obj = ServiceManager.checkService(service);
2742                if (obj != null) {
2743                    Parcel data = Parcel.obtain();
2744                    try {
2745                        obj.transact(IBinder.SYSPROPS_TRANSACTION, data, null, 0);
2746                    } catch (RemoteException e) {
2747                    } catch (Exception e) {
2748                        Log.i(TAG, "Someone wrote a bad service '" + service
2749                                + "' that doesn't like to be poked: " + e);
2750                    }
2751                    data.recycle();
2752                }
2753            }
2754            return null;
2755        }
2756    }
2757
2758    private static boolean isPackageInstalled(Context context, String packageName) {
2759        try {
2760            return context.getPackageManager().getPackageInfo(packageName, 0) != null;
2761        } catch (NameNotFoundException e) {
2762            return false;
2763        }
2764    }
2765
2766
2767    /**
2768     * For Search.
2769     */
2770    public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
2771            new BaseSearchIndexProvider() {
2772
2773                private boolean isShowingDeveloperOptions(Context context) {
2774                    return context.getSharedPreferences(DevelopmentSettings.PREF_FILE,
2775                            Context.MODE_PRIVATE).getBoolean(
2776                            DevelopmentSettings.PREF_SHOW,
2777                            android.os.Build.TYPE.equals("eng"));
2778                }
2779
2780                @Override
2781                public List<SearchIndexableResource> getXmlResourcesToIndex(
2782                        Context context, boolean enabled) {
2783
2784                    if (!isShowingDeveloperOptions(context)) {
2785                        return null;
2786                    }
2787
2788                    final SearchIndexableResource sir = new SearchIndexableResource(context);
2789                    sir.xmlResId = R.xml.development_prefs;
2790                    return Arrays.asList(sir);
2791                }
2792
2793                @Override
2794                public List<String> getNonIndexableKeys(Context context) {
2795                    if (!isShowingDeveloperOptions(context)) {
2796                        return null;
2797                    }
2798
2799                    final List<String> keys = new ArrayList<String>();
2800                    if (!showEnableOemUnlockPreference(context)) {
2801                        keys.add(ENABLE_OEM_UNLOCK);
2802                    }
2803                    return keys;
2804                }
2805            };
2806
2807    private void resetShortcutManagerThrottling() {
2808        final IShortcutService service = IShortcutService.Stub.asInterface(
2809                ServiceManager.getService(Context.SHORTCUT_SERVICE));
2810        if (service != null) {
2811            try {
2812                service.resetThrottling();
2813                Toast.makeText(getActivity(), R.string.reset_shortcut_manager_throttling_complete,
2814                        Toast.LENGTH_SHORT).show();
2815            } catch (RemoteException e) {
2816                Log.e(TAG, "Failed to reset rate limiting", e);
2817            }
2818        }
2819    }
2820
2821    private void updateOemUnlockSettingDescription() {
2822        if (mEnableOemUnlock != null) {
2823            int oemUnlockSummary = R.string.oem_unlock_enable_summary;
2824            if (isBootloaderUnlocked()) {
2825                oemUnlockSummary = R.string.oem_unlock_enable_disabled_summary_bootloader_unlocked;
2826            } else if (isSimLockedDevice()) {
2827                oemUnlockSummary = R.string.oem_unlock_enable_disabled_summary_sim_locked_device;
2828            } else if (!mOemLockManager.canUserAllowOemUnlock()) {
2829                // If the device isn't SIM-locked but OEM unlock is disallowed by some party, this
2830                // means either some other carrier restriction is in place or the device hasn't been
2831                // able to confirm which restrictions (SIM-lock or otherwise) apply.
2832                oemUnlockSummary =
2833                        R.string.oem_unlock_enable_disabled_summary_connectivity_or_locked;
2834            }
2835            mEnableOemUnlock.setSummary(getString(oemUnlockSummary));
2836        }
2837    }
2838
2839    /** Returns {@code true} if the device is SIM-locked. Otherwise, returns {@code false}. */
2840    private boolean isSimLockedDevice() {
2841        int phoneCount = mTelephonyManager.getPhoneCount();
2842        for (int i = 0; i < phoneCount; i++) {
2843            if (mTelephonyManager.getAllowedCarriers(i).size() > 0) {
2844                return true;
2845            }
2846        }
2847        return false;
2848    }
2849
2850    /**
2851     * Returns {@code true} if the bootloader has been unlocked. Otherwise, returns {code false}.
2852     */
2853    private boolean isBootloaderUnlocked() {
2854        return mOemLockManager.isDeviceOemUnlocked();
2855    }
2856
2857
2858}
2859