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