OSDN Git Service

development: Add setting for updating recovery
[android-x86/packages-apps-Settings.git] / src / com / android / settings / DevelopmentSettings.java
1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  * Copyright (C) 2013-2014 The CyanogenMod Project
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 package com.android.settings;
19
20 import android.Manifest;
21 import android.app.Activity;
22 import android.app.ActivityManagerNative;
23 import android.app.AlertDialog;
24 import android.app.AppOpsManager;
25 import android.app.AppOpsManager.PackageOps;
26 import android.app.Dialog;
27 import android.app.admin.DevicePolicyManager;
28 import android.app.backup.IBackupManager;
29 import android.bluetooth.BluetoothAdapter;
30 import android.content.BroadcastReceiver;
31 import android.content.ComponentName;
32 import android.content.ContentResolver;
33 import android.content.Context;
34 import android.content.DialogInterface;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.content.pm.ApplicationInfo;
38 import android.content.pm.PackageManager;
39 import android.content.pm.PackageManager.NameNotFoundException;
40 import android.content.pm.ResolveInfo;
41 import android.content.res.Resources;
42 import android.net.NetworkUtils;
43 import android.net.wifi.IWifiManager;
44 import android.net.wifi.WifiInfo;
45 import android.hardware.usb.IUsbManager;
46 import android.hardware.usb.UsbManager;
47 import android.net.wifi.WifiManager;
48 import android.os.AsyncTask;
49 import android.os.BatteryManager;
50 import android.os.Build;
51 import android.os.Bundle;
52 import android.os.IBinder;
53 import android.os.Parcel;
54 import android.os.RemoteException;
55 import android.os.ServiceManager;
56 import android.os.StrictMode;
57 import android.os.SystemProperties;
58 import android.os.UserHandle;
59 import android.os.UserManager;
60 import android.preference.ListPreference;
61 import android.preference.Preference;
62 import android.preference.Preference.OnPreferenceChangeListener;
63 import android.preference.PreferenceGroup;
64 import android.preference.PreferenceScreen;
65 import android.preference.SwitchPreference;
66 import android.provider.SearchIndexableResource;
67 import android.provider.Settings;
68 import android.text.TextUtils;
69 import android.util.Log;
70 import android.view.HardwareRenderer;
71 import android.view.IWindowManager;
72 import android.view.LayoutInflater;
73 import android.view.View;
74 import android.view.ViewGroup;
75 import android.view.accessibility.AccessibilityManager;
76 import android.widget.Switch;
77 import android.widget.TextView;
78
79 import com.android.internal.logging.MetricsLogger;
80 import com.android.settings.fuelgauge.InactiveApps;
81 import com.android.settings.search.BaseSearchIndexProvider;
82 import com.android.settings.search.Indexable;
83 import com.android.settings.widget.SwitchBar;
84 import cyanogenmod.providers.CMSettings;
85
86 import java.util.ArrayList;
87 import java.util.Arrays;
88 import java.util.HashSet;
89 import java.util.List;
90
91 /*
92  * Displays preferences for application developers.
93  */
94 public class DevelopmentSettings extends SettingsPreferenceFragment
95         implements DialogInterface.OnClickListener, DialogInterface.OnDismissListener,
96                 OnPreferenceChangeListener, SwitchBar.OnSwitchChangeListener, Indexable {
97     private static final String TAG = "DevelopmentSettings";
98
99     /**
100      * Preference file were development settings prefs are stored.
101      */
102     public static final String PREF_FILE = "development";
103
104     /**
105      * Whether to show the development settings to the user.  Default is false.
106      */
107     public static final String PREF_SHOW = "show";
108
109     private static final String ENABLE_ADB = "enable_adb";
110     private static final String ADB_NOTIFY = "adb_notify";
111     private static final String ADB_TCPIP = "adb_over_network";
112     private static final String CLEAR_ADB_KEYS = "clear_adb_keys";
113     private static final String ENABLE_TERMINAL = "enable_terminal";
114     private static final String KEEP_SCREEN_ON_MODES = "keep_screen_on_modes";
115     private static final String BT_HCI_SNOOP_LOG = "bt_hci_snoop_log";
116     private static final String ENABLE_OEM_UNLOCK = "oem_unlock_enable";
117     private static final String HDCP_CHECKING_KEY = "hdcp_checking";
118     private static final String HDCP_CHECKING_PROPERTY = "persist.sys.hdcp_checking";
119     private static final String LOCAL_BACKUP_PASSWORD = "local_backup_password";
120     private static final String HARDWARE_UI_PROPERTY = "persist.sys.ui.hw";
121     private static final String MSAA_PROPERTY = "debug.egl.force_msaa";
122     private static final String BUGREPORT = "bugreport";
123     private static final String BUGREPORT_IN_POWER_KEY = "bugreport_in_power";
124     private static final String OPENGL_TRACES_PROPERTY = "debug.egl.trace";
125     private static final String TUNER_UI_KEY = "tuner_ui";
126
127     private static final String DEBUG_APP_KEY = "debug_app";
128     private static final String WAIT_FOR_DEBUGGER_KEY = "wait_for_debugger";
129     private static final String MOCK_LOCATION_APP_KEY = "mock_location_app";
130     private static final String VERIFY_APPS_OVER_USB_KEY = "verify_apps_over_usb";
131     private static final String DEBUG_VIEW_ATTRIBUTES =  "debug_view_attributes";
132     private static final String STRICT_MODE_KEY = "strict_mode";
133     private static final String POINTER_LOCATION_KEY = "pointer_location";
134     private static final String SHOW_TOUCHES_KEY = "show_touches";
135     private static final String SHOW_SCREEN_UPDATES_KEY = "show_screen_updates";
136     private static final String DISABLE_OVERLAYS_KEY = "disable_overlays";
137     private static final String SIMULATE_COLOR_SPACE = "simulate_color_space";
138     private static final String USB_AUDIO_KEY = "usb_audio";
139     private static final String SHOW_CPU_USAGE_KEY = "show_cpu_usage";
140     private static final String FORCE_HARDWARE_UI_KEY = "force_hw_ui";
141     private static final String FORCE_MSAA_KEY = "force_msaa";
142     private static final String TRACK_FRAME_TIME_KEY = "track_frame_time";
143     private static final String SHOW_NON_RECTANGULAR_CLIP_KEY = "show_non_rect_clip";
144     private static final String SHOW_HW_SCREEN_UPDATES_KEY = "show_hw_screen_udpates";
145     private static final String SHOW_HW_LAYERS_UPDATES_KEY = "show_hw_layers_udpates";
146     private static final String DEBUG_HW_OVERDRAW_KEY = "debug_hw_overdraw";
147     private static final String DEBUG_LAYOUT_KEY = "debug_layout";
148     private static final String FORCE_RTL_LAYOUT_KEY = "force_rtl_layout_all_locales";
149     private static final String WINDOW_ANIMATION_SCALE_KEY = "window_animation_scale";
150     private static final String TRANSITION_ANIMATION_SCALE_KEY = "transition_animation_scale";
151     private static final String ANIMATOR_DURATION_SCALE_KEY = "animator_duration_scale";
152     private static final String OVERLAY_DISPLAY_DEVICES_KEY = "overlay_display_devices";
153     private static final String ENABLE_MULTI_WINDOW_KEY = "enable_multi_window";
154     private static final String DEBUG_DEBUGGING_CATEGORY_KEY = "debug_debugging_category";
155     private static final String SELECT_LOGD_SIZE_KEY = "select_logd_size";
156     private static final String SELECT_LOGD_SIZE_PROPERTY = "persist.logd.size";
157     private static final String SELECT_LOGD_DEFAULT_SIZE_PROPERTY = "ro.logd.size";
158
159     private static final String WIFI_DISPLAY_CERTIFICATION_KEY = "wifi_display_certification";
160     private static final String WIFI_VERBOSE_LOGGING_KEY = "wifi_verbose_logging";
161     private static final String WIFI_AGGRESSIVE_HANDOVER_KEY = "wifi_aggressive_handover";
162     private static final String WIFI_ALLOW_SCAN_WITH_TRAFFIC_KEY = "wifi_allow_scan_with_traffic";
163     private static final String USB_CONFIGURATION_KEY = "select_usb_configuration";
164     private static final String WIFI_LEGACY_DHCP_CLIENT_KEY = "legacy_dhcp_client";
165     private static final String MOBILE_DATA_ALWAYS_ON = "mobile_data_always_on";
166     private static final String KEY_COLOR_MODE = "color_mode";
167
168     private static final String INACTIVE_APPS_KEY = "inactive_apps";
169
170     private static final String OPENGL_TRACES_KEY = "enable_opengl_traces";
171
172     private static final String ROOT_ACCESS_KEY = "root_access";
173     private static final String ROOT_ACCESS_PROPERTY = "persist.sys.root_access";
174
175     private static final String UPDATE_RECOVERY_KEY = "update_recovery";
176     private static final String UPDATE_RECOVERY_PROPERTY = "persist.sys.recovery_update";
177
178     private static final String IMMEDIATELY_DESTROY_ACTIVITIES_KEY
179             = "immediately_destroy_activities";
180     private static final String APP_PROCESS_LIMIT_KEY = "app_process_limit";
181
182     private static final String SHOW_ALL_ANRS_KEY = "show_all_anrs";
183
184     private static final String KILL_APP_LONGPRESS_BACK = "kill_app_longpress_back";
185
186     private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
187
188     private static final String TERMINAL_APP_PACKAGE = "com.android.terminal";
189
190     private static final String DEVELOPMENT_TOOLS = "development_tools";
191
192     private static final String ADVANCED_REBOOT_KEY = "advanced_reboot";
193
194     private static final String DEVELOPMENT_SHORTCUT_KEY = "development_shortcut";
195
196     private static final int RESULT_DEBUG_APP = 1000;
197     private static final int RESULT_MOCK_LOCATION_APP = 1001;
198
199     private static final String PERSISTENT_DATA_BLOCK_PROP = "ro.frp.pst";
200
201     private static final int REQUEST_CODE_ENABLE_OEM_UNLOCK = 0;
202
203     private static String DEFAULT_LOG_RING_BUFFER_SIZE_IN_BYTES = "262144"; // 256K
204
205     private static final int[] MOCK_LOCATION_APP_OPS = new int[] {AppOpsManager.OP_MOCK_LOCATION};
206
207     private static final String MULTI_WINDOW_SYSTEM_PROPERTY = "persist.sys.debug.multi_window";
208     private IWindowManager mWindowManager;
209     private IBackupManager mBackupManager;
210     private DevicePolicyManager mDpm;
211     private UserManager mUm;
212     private WifiManager mWifiManager;
213
214     private SwitchBar mSwitchBar;
215     private boolean mLastEnabledState;
216     private boolean mHaveDebugSettings;
217     private boolean mDontPokeProperties;
218
219     private SwitchPreference mEnableAdb;
220     private SwitchPreference mAdbNotify;
221     private SwitchPreference mAdbOverNetwork;
222     private Preference mClearAdbKeys;
223     private SwitchPreference mEnableTerminal;
224     private Preference mBugreport;
225     private SwitchPreference mBugreportInPower;
226     private ListPreference mKeepScreenOn;
227     private SwitchPreference mBtHciSnoopLog;
228     private SwitchPreference mEnableOemUnlock;
229     private SwitchPreference mDebugViewAttributes;
230
231     private PreferenceScreen mPassword;
232     private String mDebugApp;
233     private Preference mDebugAppPref;
234
235     private String mMockLocationApp;
236     private Preference mMockLocationAppPref;
237
238     private SwitchPreference mWaitForDebugger;
239     private SwitchPreference mVerifyAppsOverUsb;
240     private SwitchPreference mWifiDisplayCertification;
241     private SwitchPreference mWifiVerboseLogging;
242     private SwitchPreference mWifiAggressiveHandover;
243     private SwitchPreference mLegacyDhcpClient;
244     private SwitchPreference mMobileDataAlwaysOn;
245
246     private SwitchPreference mWifiAllowScansWithTraffic;
247     private SwitchPreference mStrictMode;
248     private SwitchPreference mPointerLocation;
249     private SwitchPreference mShowTouches;
250     private SwitchPreference mShowScreenUpdates;
251     private SwitchPreference mDisableOverlays;
252     private SwitchPreference mEnableMultiWindow;
253     private SwitchPreference mShowCpuUsage;
254     private SwitchPreference mForceHardwareUi;
255     private SwitchPreference mForceMsaa;
256     private SwitchPreference mShowHwScreenUpdates;
257     private SwitchPreference mShowHwLayersUpdates;
258     private SwitchPreference mDebugLayout;
259     private SwitchPreference mForceRtlLayout;
260     private ListPreference mDebugHwOverdraw;
261     private ListPreference mLogdSize;
262     private ListPreference mUsbConfiguration;
263     private ListPreference mTrackFrameTime;
264     private ListPreference mShowNonRectClip;
265     private ListPreference mWindowAnimationScale;
266     private ListPreference mTransitionAnimationScale;
267     private ListPreference mAnimatorDurationScale;
268     private ListPreference mOverlayDisplayDevices;
269     private ListPreference mOpenGLTraces;
270
271     private ListPreference mSimulateColorSpace;
272
273     private SwitchPreference mUSBAudio;
274     private SwitchPreference mImmediatelyDestroyActivities;
275
276     private ListPreference mAppProcessLimit;
277
278     private SwitchPreference mShowAllANRs;
279     private SwitchPreference mKillAppLongpressBack;
280
281     private ListPreference mRootAccess;
282     private Object mSelectedRootValue;
283     private PreferenceScreen mDevelopmentTools;
284     private ColorModePreference mColorModePreference;
285
286     private SwitchPreference mAdvancedReboot;
287
288     private SwitchPreference mUpdateRecovery;
289
290     private SwitchPreference mDevelopmentShortcut;
291
292     private final ArrayList<Preference> mAllPrefs = new ArrayList<Preference>();
293
294     private final ArrayList<SwitchPreference> mResetSwitchPrefs
295             = new ArrayList<SwitchPreference>();
296
297     private final HashSet<Preference> mDisabledPrefs = new HashSet<Preference>();
298     // To track whether a confirmation dialog was clicked.
299     private boolean mDialogClicked;
300     private Dialog mEnableDialog;
301     private Dialog mAdbDialog;
302     private Dialog mAdbTcpDialog;
303     private Dialog mAdbKeysDialog;
304     private boolean mUnavailable;
305     private Dialog mRootDialog;
306     private Dialog mUpdateRecoveryDialog;
307
308     @Override
309     protected int getMetricsCategory() {
310         return MetricsLogger.DEVELOPMENT;
311     }
312
313     @Override
314     public void onCreate(Bundle icicle) {
315         super.onCreate(icicle);
316
317         mWindowManager = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
318         mBackupManager = IBackupManager.Stub.asInterface(
319                 ServiceManager.getService(Context.BACKUP_SERVICE));
320         mDpm = (DevicePolicyManager)getActivity().getSystemService(Context.DEVICE_POLICY_SERVICE);
321         mUm = (UserManager) getSystemService(Context.USER_SERVICE);
322
323         mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
324
325         if (android.os.Process.myUserHandle().getIdentifier() != UserHandle.USER_OWNER
326                 || mUm.hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
327             mUnavailable = true;
328             setPreferenceScreen(new PreferenceScreen(getActivity(), null));
329             return;
330         }
331
332         addPreferencesFromResource(R.xml.development_prefs);
333
334         final PreferenceGroup debugDebuggingCategory = (PreferenceGroup)
335                 findPreference(DEBUG_DEBUGGING_CATEGORY_KEY);
336         mEnableAdb = findAndInitSwitchPref(ENABLE_ADB);
337
338         mAdbNotify = findAndInitSwitchPref(ADB_NOTIFY);
339         mAllPrefs.add(mAdbNotify);
340         mAdbOverNetwork = findAndInitSwitchPref(ADB_TCPIP);
341
342         mClearAdbKeys = findPreference(CLEAR_ADB_KEYS);
343         if (!SystemProperties.getBoolean("ro.adb.secure", false)) {
344             if (debugDebuggingCategory != null) {
345                 debugDebuggingCategory.removePreference(mClearAdbKeys);
346             }
347         }
348         mAllPrefs.add(mClearAdbKeys);
349         mEnableTerminal = findAndInitSwitchPref(ENABLE_TERMINAL);
350         if (!isPackageInstalled(getActivity(), TERMINAL_APP_PACKAGE)) {
351             debugDebuggingCategory.removePreference(mEnableTerminal);
352             mEnableTerminal = null;
353         }
354
355         mBugreport = findPreference(BUGREPORT);
356         mBugreportInPower = findAndInitSwitchPref(BUGREPORT_IN_POWER_KEY);
357         mKeepScreenOn = addListPreference(KEEP_SCREEN_ON_MODES);
358         mBtHciSnoopLog = findAndInitSwitchPref(BT_HCI_SNOOP_LOG);
359         mEnableOemUnlock = findAndInitSwitchPref(ENABLE_OEM_UNLOCK);
360         if (!showEnableOemUnlockPreference()) {
361             removePreference(mEnableOemUnlock);
362             mEnableOemUnlock = null;
363         }
364
365         mDebugViewAttributes = findAndInitSwitchPref(DEBUG_VIEW_ATTRIBUTES);
366         mPassword = (PreferenceScreen) findPreference(LOCAL_BACKUP_PASSWORD);
367         mAllPrefs.add(mPassword);
368         mAdvancedReboot = findAndInitSwitchPref(ADVANCED_REBOOT_KEY);
369         mUpdateRecovery = findAndInitSwitchPref(UPDATE_RECOVERY_KEY);
370         mDevelopmentShortcut = findAndInitSwitchPref(DEVELOPMENT_SHORTCUT_KEY);
371
372
373         if (!android.os.Process.myUserHandle().equals(UserHandle.OWNER)) {
374             disableForUser(mEnableAdb);
375             disableForUser(mClearAdbKeys);
376             disableForUser(mEnableTerminal);
377             disableForUser(mPassword);
378             disableForUser(mAdvancedReboot);
379             disableForUser(mUpdateRecovery);
380             disableForUser(mDevelopmentShortcut);
381         }
382
383         mDebugAppPref = findPreference(DEBUG_APP_KEY);
384         mAllPrefs.add(mDebugAppPref);
385         mWaitForDebugger = findAndInitSwitchPref(WAIT_FOR_DEBUGGER_KEY);
386
387         mMockLocationAppPref = findPreference(MOCK_LOCATION_APP_KEY);
388         mAllPrefs.add(mMockLocationAppPref);
389
390         mVerifyAppsOverUsb = findAndInitSwitchPref(VERIFY_APPS_OVER_USB_KEY);
391         if (!showVerifierSetting()) {
392             if (debugDebuggingCategory != null) {
393                 debugDebuggingCategory.removePreference(mVerifyAppsOverUsb);
394             } else {
395                 mVerifyAppsOverUsb.setEnabled(false);
396             }
397         }
398         mStrictMode = findAndInitSwitchPref(STRICT_MODE_KEY);
399         mPointerLocation = findAndInitSwitchPref(POINTER_LOCATION_KEY);
400         mShowTouches = findAndInitSwitchPref(SHOW_TOUCHES_KEY);
401         mShowScreenUpdates = findAndInitSwitchPref(SHOW_SCREEN_UPDATES_KEY);
402         mDisableOverlays = findAndInitSwitchPref(DISABLE_OVERLAYS_KEY);
403         mShowCpuUsage = findAndInitSwitchPref(SHOW_CPU_USAGE_KEY);
404         mForceHardwareUi = findAndInitSwitchPref(FORCE_HARDWARE_UI_KEY);
405         mForceMsaa = findAndInitSwitchPref(FORCE_MSAA_KEY);
406         mTrackFrameTime = addListPreference(TRACK_FRAME_TIME_KEY);
407         mShowNonRectClip = addListPreference(SHOW_NON_RECTANGULAR_CLIP_KEY);
408         mShowHwScreenUpdates = findAndInitSwitchPref(SHOW_HW_SCREEN_UPDATES_KEY);
409         mShowHwLayersUpdates = findAndInitSwitchPref(SHOW_HW_LAYERS_UPDATES_KEY);
410         mDebugLayout = findAndInitSwitchPref(DEBUG_LAYOUT_KEY);
411         mForceRtlLayout = findAndInitSwitchPref(FORCE_RTL_LAYOUT_KEY);
412         mDebugHwOverdraw = addListPreference(DEBUG_HW_OVERDRAW_KEY);
413         mWifiDisplayCertification = findAndInitSwitchPref(WIFI_DISPLAY_CERTIFICATION_KEY);
414         mWifiVerboseLogging = findAndInitSwitchPref(WIFI_VERBOSE_LOGGING_KEY);
415         mWifiAggressiveHandover = findAndInitSwitchPref(WIFI_AGGRESSIVE_HANDOVER_KEY);
416         mWifiAllowScansWithTraffic = findAndInitSwitchPref(WIFI_ALLOW_SCAN_WITH_TRAFFIC_KEY);
417         mLegacyDhcpClient = findAndInitSwitchPref(WIFI_LEGACY_DHCP_CLIENT_KEY);
418         mMobileDataAlwaysOn = findAndInitSwitchPref(MOBILE_DATA_ALWAYS_ON);
419         mLogdSize = addListPreference(SELECT_LOGD_SIZE_KEY);
420         mUsbConfiguration = addListPreference(USB_CONFIGURATION_KEY);
421
422         mWindowAnimationScale = addListPreference(WINDOW_ANIMATION_SCALE_KEY);
423         mTransitionAnimationScale = addListPreference(TRANSITION_ANIMATION_SCALE_KEY);
424         mAnimatorDurationScale = addListPreference(ANIMATOR_DURATION_SCALE_KEY);
425         mOverlayDisplayDevices = addListPreference(OVERLAY_DISPLAY_DEVICES_KEY);
426         mEnableMultiWindow = findAndInitSwitchPref(ENABLE_MULTI_WINDOW_KEY);
427         if (!showEnableMultiWindowPreference()) {
428             final PreferenceGroup drawingGroup =
429                     (PreferenceGroup)findPreference("debug_drawing_category");
430             if (drawingGroup != null) {
431                 drawingGroup.removePreference(mEnableMultiWindow);
432             } else {
433                 mEnableMultiWindow.setEnabled(false);
434             }
435             removePreference(mEnableMultiWindow);
436             mEnableMultiWindow = null;
437         }
438         mOpenGLTraces = addListPreference(OPENGL_TRACES_KEY);
439         mSimulateColorSpace = addListPreference(SIMULATE_COLOR_SPACE);
440         mUSBAudio = findAndInitSwitchPref(USB_AUDIO_KEY);
441
442         mImmediatelyDestroyActivities = (SwitchPreference) findPreference(
443                 IMMEDIATELY_DESTROY_ACTIVITIES_KEY);
444         mAllPrefs.add(mImmediatelyDestroyActivities);
445         mResetSwitchPrefs.add(mImmediatelyDestroyActivities);
446
447         mAppProcessLimit = addListPreference(APP_PROCESS_LIMIT_KEY);
448
449         mShowAllANRs = (SwitchPreference) findPreference(
450                 SHOW_ALL_ANRS_KEY);
451         mAllPrefs.add(mShowAllANRs);
452         mResetSwitchPrefs.add(mShowAllANRs);
453
454         mKillAppLongpressBack = findAndInitSwitchPref(KILL_APP_LONGPRESS_BACK);
455
456         Preference hdcpChecking = findPreference(HDCP_CHECKING_KEY);
457         if (hdcpChecking != null) {
458             mAllPrefs.add(hdcpChecking);
459             removePreferenceForProduction(hdcpChecking);
460         }
461
462         mRootAccess = (ListPreference) findPreference(ROOT_ACCESS_KEY);
463         mRootAccess.setOnPreferenceChangeListener(this);
464         if (!removeRootOptionsIfRequired()) {
465             mAllPrefs.add(mRootAccess);
466         }
467
468         mDevelopmentTools = (PreferenceScreen) findPreference(DEVELOPMENT_TOOLS);
469         if (Utils.updatePreferenceToSpecificActivityOrRemove(getActivity(),
470                 getPreferenceScreen(), mDevelopmentTools.getKey(), 0)) {
471             mAllPrefs.add(mDevelopmentTools);
472         }
473
474         mColorModePreference = (ColorModePreference) findPreference(KEY_COLOR_MODE);
475         mColorModePreference.updateCurrentAndSupported();
476         if (mColorModePreference.getTransformsCount() < 2) {
477             removePreference(KEY_COLOR_MODE);
478             mColorModePreference = null;
479         }
480     }
481
482     private ListPreference addListPreference(String prefKey) {
483         ListPreference pref = (ListPreference) findPreference(prefKey);
484         mAllPrefs.add(pref);
485         pref.setOnPreferenceChangeListener(this);
486         return pref;
487     }
488
489     private void disableForUser(Preference pref) {
490         if (pref != null) {
491             pref.setEnabled(false);
492             mDisabledPrefs.add(pref);
493         }
494     }
495
496     private SwitchPreference findAndInitSwitchPref(String key) {
497         SwitchPreference pref = (SwitchPreference) findPreference(key);
498         if (pref == null) {
499             throw new IllegalArgumentException("Cannot find preference with key = " + key);
500         }
501         mAllPrefs.add(pref);
502         mResetSwitchPrefs.add(pref);
503         return pref;
504     }
505
506     private boolean removeRootOptionsIfRequired() {
507         // user builds don't get root, and eng always gets root
508         if (!(Build.IS_DEBUGGABLE || "eng".equals(Build.TYPE))) {
509             if (mRootAccess != null) {
510                 getPreferenceScreen().removePreference(mRootAccess);
511                 return true;
512             }
513         }
514
515         return false;
516     }
517
518     @Override
519     public void onActivityCreated(Bundle savedInstanceState) {
520         super.onActivityCreated(savedInstanceState);
521
522         final SettingsActivity activity = (SettingsActivity) getActivity();
523
524         mSwitchBar = activity.getSwitchBar();
525        if (mUnavailable) {
526             mSwitchBar.setEnabled(false);
527             return;
528         }
529
530         mSwitchBar.addOnSwitchChangeListener(this);
531     }
532
533     private boolean removePreferenceForProduction(Preference preference) {
534         if ("user".equals(Build.TYPE)) {
535             removePreference(preference);
536             return true;
537         }
538         return false;
539     }
540
541     private void removePreference(Preference preference) {
542         getPreferenceScreen().removePreference(preference);
543         mAllPrefs.remove(preference);
544         mResetSwitchPrefs.remove(preference);
545     }
546
547     private void setPrefsEnabledState(boolean enabled) {
548         for (int i = 0; i < mAllPrefs.size(); i++) {
549             Preference pref = mAllPrefs.get(i);
550             pref.setEnabled(enabled && !mDisabledPrefs.contains(pref));
551         }
552         updateAllOptions();
553     }
554
555     @Override
556     public void onResume() {
557         super.onResume();
558
559         if (mUnavailable) {
560             // Show error message
561             TextView emptyView = (TextView) getView().findViewById(android.R.id.empty);
562             getListView().setEmptyView(emptyView);
563             if (emptyView != null) {
564                 emptyView.setText(R.string.development_settings_not_available);
565             }
566             return;
567         }
568
569         if (mDpm.getMaximumTimeToLock(null) > 0) {
570             // A DeviceAdmin has specified a maximum time until the device
571             // will lock...  in this case we can't allow the user to turn
572             // on "stay awake when plugged in" because that would defeat the
573             // restriction.
574             mDisabledPrefs.add(mKeepScreenOn);
575         } else {
576             mDisabledPrefs.remove(mKeepScreenOn);
577         }
578
579         final ContentResolver cr = getActivity().getContentResolver();
580         mLastEnabledState = Settings.Global.getInt(cr,
581                 Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0;
582         mSwitchBar.setChecked(mLastEnabledState);
583         setPrefsEnabledState(mLastEnabledState);
584
585         if (mHaveDebugSettings && !mLastEnabledState) {
586             // Overall debugging is disabled, but there are some debug
587             // settings that are enabled.  This is an invalid state.  Switch
588             // to debug settings being enabled, so the user knows there is
589             // stuff enabled and can turn it all off if they want.
590             Settings.Global.putInt(getActivity().getContentResolver(),
591                     Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 1);
592             mLastEnabledState = true;
593             mSwitchBar.setChecked(mLastEnabledState);
594             setPrefsEnabledState(mLastEnabledState);
595         }
596         mSwitchBar.show();
597         updateKillAppLongpressBackOptions();
598
599         if (mColorModePreference != null) {
600             mColorModePreference.startListening();
601             mColorModePreference.updateCurrentAndSupported();
602         }
603     }
604
605     @Override
606     public void onPause() {
607         super.onPause();
608         if (mColorModePreference != null) {
609             mColorModePreference.stopListening();
610         }
611     }
612
613     @Override
614     public View onCreateView(LayoutInflater inflater, ViewGroup container,
615             Bundle savedInstanceState) {
616         IntentFilter filter = new IntentFilter();
617         filter.addAction(UsbManager.ACTION_USB_STATE);
618         getActivity().registerReceiver(mUsbReceiver, filter);
619         return super.onCreateView(inflater, container, savedInstanceState);
620     }
621
622     @Override
623     public void onDestroyView() {
624         super.onDestroyView();
625
626         if (mUnavailable) {
627             return;
628         }
629         mSwitchBar.removeOnSwitchChangeListener(this);
630         mSwitchBar.hide();
631         getActivity().unregisterReceiver(mUsbReceiver);
632     }
633
634     void updateSwitchPreference(SwitchPreference switchPreference, boolean value) {
635         switchPreference.setChecked(value);
636         mHaveDebugSettings |= value;
637     }
638
639     private void updateAllOptions() {
640         final Context context = getActivity();
641         final ContentResolver cr = context.getContentResolver();
642         mHaveDebugSettings = false;
643         updateSwitchPreference(mEnableAdb, Settings.Global.getInt(cr,
644                 Settings.Global.ADB_ENABLED, 0) != 0);
645
646         mAdbNotify.setChecked(CMSettings.Secure.getInt(cr,
647                 CMSettings.Secure.ADB_NOTIFY, 1) != 0);
648         updateAdbOverNetwork();
649
650         if (mEnableTerminal != null) {
651             updateSwitchPreference(mEnableTerminal,
652                     context.getPackageManager().getApplicationEnabledSetting(TERMINAL_APP_PACKAGE)
653                             == PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
654         }
655         updateSwitchPreference(mBugreportInPower, Settings.Secure.getInt(cr,
656                 Settings.Secure.BUGREPORT_IN_POWER_MENU, 0) != 0);
657         updateStayAwakeOptions();
658         updateSwitchPreference(mBtHciSnoopLog, Settings.Secure.getInt(cr,
659                 Settings.Secure.BLUETOOTH_HCI_LOG, 0) != 0);
660         if (mEnableOemUnlock != null) {
661             updateSwitchPreference(mEnableOemUnlock, Utils.isOemUnlockEnabled(getActivity()));
662         }
663         updateSwitchPreference(mDebugViewAttributes, Settings.Global.getInt(cr,
664                 Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0);
665         updateHdcpValues();
666         updatePasswordSummary();
667         updateDebuggerOptions();
668         updateMockLocation();
669         updateStrictModeVisualOptions();
670         updatePointerLocationOptions();
671         updateShowTouchesOptions();
672         updateFlingerOptions();
673         updateCpuUsageOptions();
674         updateHardwareUiOptions();
675         updateMsaaOptions();
676         updateTrackFrameTimeOptions();
677         updateShowNonRectClipOptions();
678         updateShowHwScreenUpdatesOptions();
679         updateShowHwLayersUpdatesOptions();
680         updateDebugHwOverdrawOptions();
681         updateDebugLayoutOptions();
682         updateAnimationScaleOptions();
683         updateOverlayDisplayDevicesOptions();
684         if (mEnableMultiWindow != null) {
685             updateSwitchPreference(mEnableMultiWindow,
686                     SystemProperties.getBoolean(MULTI_WINDOW_SYSTEM_PROPERTY, false));
687         }
688         updateOpenGLTracesOptions();
689         updateImmediatelyDestroyActivitiesOptions();
690         updateAppProcessLimitOptions();
691         updateShowAllANRsOptions();
692         updateVerifyAppsOverUsbOptions();
693         updateBugreportOptions();
694         updateForceRtlOptions();
695         updateLogdSizeValues();
696         updateWifiDisplayCertificationOptions();
697         updateWifiVerboseLoggingOptions();
698         updateWifiAggressiveHandoverOptions();
699         updateWifiAllowScansWithTrafficOptions();
700         updateLegacyDhcpClientOptions();
701         updateMobileDataAlwaysOnOptions();
702         updateSimulateColorSpace();
703         updateUSBAudioOptions();
704         updateRootAccessOptions();
705         updateAdvancedRebootOptions();
706         updateDevelopmentShortcutOptions();
707         updateUpdateRecoveryOptions();
708     }
709
710     private void writeAdvancedRebootOptions() {
711         CMSettings.Secure.putInt(getActivity().getContentResolver(),
712                 CMSettings.Secure.ADVANCED_REBOOT,
713                 mAdvancedReboot.isChecked() ? 1 : 0);
714     }
715
716     private void updateAdvancedRebootOptions() {
717         mAdvancedReboot.setChecked(CMSettings.Secure.getInt(getActivity().getContentResolver(),
718                 CMSettings.Secure.ADVANCED_REBOOT, 0) != 0);
719     }
720
721     private void resetDevelopmentShortcutOptions() {
722         CMSettings.Secure.putInt(getActivity().getContentResolver(),
723                 CMSettings.Secure.DEVELOPMENT_SHORTCUT, 0);
724     }
725
726     private void writeDevelopmentShortcutOptions() {
727         CMSettings.Secure.putInt(getActivity().getContentResolver(),
728                 CMSettings.Secure.DEVELOPMENT_SHORTCUT,
729                 mDevelopmentShortcut.isChecked() ? 1 : 0);
730     }
731
732     private void updateDevelopmentShortcutOptions() {
733         mDevelopmentShortcut.setChecked(CMSettings.Secure.getInt(getActivity().getContentResolver(),
734                 CMSettings.Secure.DEVELOPMENT_SHORTCUT, 0) != 0);
735     }
736
737     private void updateAdbOverNetwork() {
738         int port = CMSettings.Secure.getInt(getActivity().getContentResolver(),
739                 CMSettings.Secure.ADB_PORT, 0);
740         boolean enabled = port > 0;
741
742         updateSwitchPreference(mAdbOverNetwork, enabled);
743
744         WifiInfo wifiInfo = null;
745
746         if (enabled) {
747             IWifiManager wifiManager = IWifiManager.Stub.asInterface(
748                     ServiceManager.getService(Context.WIFI_SERVICE));
749             try {
750                 wifiInfo = wifiManager.getConnectionInfo();
751             } catch (RemoteException e) {
752                 Log.e(TAG, "wifiManager, getConnectionInfo()", e);
753             }
754         }
755
756         if (wifiInfo != null) {
757             String hostAddress = NetworkUtils.intToInetAddress(
758                     wifiInfo.getIpAddress()).getHostAddress();
759             mAdbOverNetwork.setSummary(hostAddress + ":" + String.valueOf(port));
760         } else {
761             mAdbOverNetwork.setSummary(R.string.adb_over_network_summary);
762         }
763     }
764
765     private void resetDangerousOptions() {
766         mDontPokeProperties = true;
767         for (int i=0; i< mResetSwitchPrefs.size(); i++) {
768             SwitchPreference cb = mResetSwitchPrefs.get(i);
769             if (cb.isChecked()) {
770                 cb.setChecked(false);
771                 onPreferenceTreeClick(null, cb);
772             }
773         }
774         resetDebuggerOptions();
775         writeLogdSizeOption(null);
776         resetRootAccessOptions();
777         resetDevelopmentShortcutOptions();
778         resetUpdateRecoveryOptions();
779         writeAnimationScaleOption(0, mWindowAnimationScale, null);
780         writeAnimationScaleOption(1, mTransitionAnimationScale, null);
781         writeAnimationScaleOption(2, mAnimatorDurationScale, null);
782         // Only poke the color space setting if we control it.
783         if (usingDevelopmentColorSpace()) {
784             writeSimulateColorSpace(-1);
785         }
786         writeOverlayDisplayDevicesOptions(null);
787         writeAppProcessLimitOptions(null);
788         mHaveDebugSettings = false;
789         updateAllOptions();
790         mDontPokeProperties = false;
791         pokeSystemProperties();
792     }
793
794    private void updateRootAccessOptions() {
795         String value = SystemProperties.get(ROOT_ACCESS_PROPERTY, "0");
796         mRootAccess.setValue(value);
797         mRootAccess.setSummary(getResources()
798                 .getStringArray(R.array.root_access_entries)[Integer.valueOf(value)]);
799     }
800
801     public static boolean isRootForAppsEnabled() {
802         int value = SystemProperties.getInt(ROOT_ACCESS_PROPERTY, 0);
803         boolean daemonState =
804                 SystemProperties.get("init.svc.su_daemon", "absent").equals("running");
805         return daemonState && (value == 1 || value == 3);
806     }
807
808     private void writeRootAccessOptions(Object newValue) {
809         String oldValue = SystemProperties.get(ROOT_ACCESS_PROPERTY, "0");
810         SystemProperties.set(ROOT_ACCESS_PROPERTY, newValue.toString());
811         if (Integer.valueOf(newValue.toString()) < 2 && !oldValue.equals(newValue)
812                 && "1".equals(SystemProperties.get("service.adb.root", "0"))) {
813             SystemProperties.set("service.adb.root", "0");
814             Settings.Secure.putInt(getActivity().getContentResolver(),
815                     Settings.Secure.ADB_ENABLED, 0);
816             Settings.Secure.putInt(getActivity().getContentResolver(),
817                     Settings.Secure.ADB_ENABLED, 1);
818         }
819         updateRootAccessOptions();
820     }
821
822     private void resetRootAccessOptions() {
823         String oldValue = SystemProperties.get(ROOT_ACCESS_PROPERTY, "0");
824         SystemProperties.set(ROOT_ACCESS_PROPERTY, "0");
825         if (!oldValue.equals("0") && "1".equals(SystemProperties.get("service.adb.root", "0"))) {
826             SystemProperties.set("service.adb.root", "0");
827             Settings.Secure.putInt(getActivity().getContentResolver(),
828                     Settings.Secure.ADB_ENABLED, 0);
829             Settings.Secure.putInt(getActivity().getContentResolver(),
830                     Settings.Secure.ADB_ENABLED, 1);
831         }
832         updateRootAccessOptions();
833     }
834
835     private void updateStayAwakeOptions() {
836         int index = Settings.Global.getInt(getActivity().getContentResolver(),
837                 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
838         final String[] values = getResources().getStringArray(R.array.keep_screen_on_values);
839         final String[] summaries = getResources().getStringArray(R.array.keep_screen_on_titles);
840         // The old value contained 0 (disable) or 3 (BATTERY_PLUGGED_AC|BATTERY_PLUGGED_USB)
841         // Currently only have 3 values (0: Not enabled; 1: debugging over usb; >2: charging)
842         // NOTE: If we have newer values, then we need to migrate
843         // this property
844         if (index >= values.length) {
845             index = values.length - 1;
846         }
847         mKeepScreenOn.setValue(values[index]);
848         mKeepScreenOn.setSummary(summaries[index]);
849         mKeepScreenOn.setOnPreferenceChangeListener(this);
850     }
851
852     private void updateHdcpValues() {
853         ListPreference hdcpChecking = (ListPreference) findPreference(HDCP_CHECKING_KEY);
854         if (hdcpChecking != null) {
855             String currentValue = SystemProperties.get(HDCP_CHECKING_PROPERTY);
856             String[] values = getResources().getStringArray(R.array.hdcp_checking_values);
857             String[] summaries = getResources().getStringArray(R.array.hdcp_checking_summaries);
858             int index = 1; // Defaults to drm-only. Needs to match with R.array.hdcp_checking_values
859             for (int i = 0; i < values.length; i++) {
860                 if (currentValue.equals(values[i])) {
861                     index = i;
862                     break;
863                 }
864             }
865             hdcpChecking.setValue(values[index]);
866             hdcpChecking.setSummary(summaries[index]);
867             hdcpChecking.setOnPreferenceChangeListener(this);
868         }
869     }
870
871     private void writeKillAppLongpressBackOptions() {
872         CMSettings.Secure.putInt(getActivity().getContentResolver(),
873                 CMSettings.Secure.KILL_APP_LONGPRESS_BACK,
874                 mKillAppLongpressBack.isChecked() ? 1 : 0);
875     }
876
877     private void updateKillAppLongpressBackOptions() {
878         mKillAppLongpressBack.setChecked(CMSettings.Secure.getInt(
879             getActivity().getContentResolver(), CMSettings.Secure.KILL_APP_LONGPRESS_BACK, 0) != 0);
880     }
881
882     private void updatePasswordSummary() {
883         try {
884             if (mBackupManager.hasBackupPassword()) {
885                 mPassword.setSummary(R.string.local_backup_password_summary_change);
886             } else {
887                 mPassword.setSummary(R.string.local_backup_password_summary_none);
888             }
889         } catch (RemoteException e) {
890             // Not much we can do here
891         }
892     }
893
894     private void writeBtHciSnoopLogOptions() {
895         BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
896         adapter.configHciSnoopLog(mBtHciSnoopLog.isChecked());
897         Settings.Secure.putInt(getActivity().getContentResolver(),
898                 Settings.Secure.BLUETOOTH_HCI_LOG,
899                 mBtHciSnoopLog.isChecked() ? 1 : 0);
900     }
901
902     private void writeDebuggerOptions() {
903         try {
904             ActivityManagerNative.getDefault().setDebugApp(
905                 mDebugApp, mWaitForDebugger.isChecked(), true);
906         } catch (RemoteException ex) {
907         }
908     }
909
910     private void writeMockLocation() {
911         AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
912
913         // Disable the app op of the previous mock location app if such.
914         List<PackageOps> packageOps = appOpsManager.getPackagesForOps(MOCK_LOCATION_APP_OPS);
915         if (packageOps != null) {
916             // Should be one but in case we are in a bad state due to use of command line tools.
917             for (PackageOps packageOp : packageOps) {
918                 if (packageOp.getOps().get(0).getMode() != AppOpsManager.MODE_ERRORED) {
919                     String oldMockLocationApp = packageOp.getPackageName();
920                     try {
921                         ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(
922                                 oldMockLocationApp, PackageManager.GET_DISABLED_COMPONENTS);
923                         appOpsManager.setMode(AppOpsManager.OP_MOCK_LOCATION, ai.uid,
924                                 oldMockLocationApp, AppOpsManager.MODE_ERRORED);
925                     } catch (NameNotFoundException e) {
926                         /* ignore */
927                     }
928                 }
929             }
930         }
931
932         // Enable the app op of the new mock location app if such.
933         if (!TextUtils.isEmpty(mMockLocationApp)) {
934             try {
935                 ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(
936                         mMockLocationApp, PackageManager.GET_DISABLED_COMPONENTS);
937                 appOpsManager.setMode(AppOpsManager.OP_MOCK_LOCATION, ai.uid,
938                         mMockLocationApp, AppOpsManager.MODE_ALLOWED);
939             } catch (NameNotFoundException e) {
940                 /* ignore */
941             }
942         }
943     }
944
945     private static void resetDebuggerOptions() {
946         try {
947             ActivityManagerNative.getDefault().setDebugApp(
948                     null, false, true);
949         } catch (RemoteException ex) {
950         }
951     }
952
953     private void updateDebuggerOptions() {
954         mDebugApp = Settings.Global.getString(
955                 getActivity().getContentResolver(), Settings.Global.DEBUG_APP);
956         updateSwitchPreference(mWaitForDebugger, Settings.Global.getInt(
957                 getActivity().getContentResolver(), Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0);
958         if (mDebugApp != null && mDebugApp.length() > 0) {
959             String label;
960             try {
961                 ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(mDebugApp,
962                         PackageManager.GET_DISABLED_COMPONENTS);
963                 CharSequence lab = getActivity().getPackageManager().getApplicationLabel(ai);
964                 label = lab != null ? lab.toString() : mDebugApp;
965             } catch (PackageManager.NameNotFoundException e) {
966                 label = mDebugApp;
967             }
968             mDebugAppPref.setSummary(getResources().getString(R.string.debug_app_set, label));
969             mWaitForDebugger.setEnabled(true);
970             mHaveDebugSettings = true;
971         } else {
972             mDebugAppPref.setSummary(getResources().getString(R.string.debug_app_not_set));
973             mWaitForDebugger.setEnabled(false);
974         }
975     }
976
977     private void updateMockLocation() {
978         AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
979
980         List<PackageOps> packageOps = appOpsManager.getPackagesForOps(MOCK_LOCATION_APP_OPS);
981         if (packageOps != null) {
982             for (PackageOps packageOp : packageOps) {
983                 if (packageOp.getOps().get(0).getMode() == AppOpsManager.MODE_ALLOWED) {
984                     mMockLocationApp = packageOps.get(0).getPackageName();
985                     break;
986                 }
987             }
988         }
989
990         if (!TextUtils.isEmpty(mMockLocationApp)) {
991             String label = mMockLocationApp;
992             try {
993                 ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(
994                         mMockLocationApp, PackageManager.GET_DISABLED_COMPONENTS);
995                 CharSequence appLabel = getPackageManager().getApplicationLabel(ai);
996                 if (appLabel != null) {
997                     label = appLabel.toString();
998                 }
999             } catch (PackageManager.NameNotFoundException e) {
1000                 /* ignore */
1001             }
1002
1003             mMockLocationAppPref.setSummary(getString(R.string.mock_location_app_set, label));
1004             mHaveDebugSettings = true;
1005         } else {
1006             mMockLocationAppPref.setSummary(getString(R.string.mock_location_app_not_set));
1007         }
1008     }
1009
1010     private void updateVerifyAppsOverUsbOptions() {
1011         updateSwitchPreference(mVerifyAppsOverUsb, Settings.Global.getInt(getActivity().getContentResolver(),
1012                 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) != 0);
1013         mVerifyAppsOverUsb.setEnabled(enableVerifierSetting());
1014     }
1015
1016     private void writeVerifyAppsOverUsbOptions() {
1017         Settings.Global.putInt(getActivity().getContentResolver(),
1018               Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, mVerifyAppsOverUsb.isChecked() ? 1 : 0);
1019     }
1020
1021     private boolean enableVerifierSetting() {
1022         final ContentResolver cr = getActivity().getContentResolver();
1023         if (Settings.Global.getInt(cr, Settings.Global.ADB_ENABLED, 0) == 0) {
1024             return false;
1025         }
1026         if (Settings.Global.getInt(cr, Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 0) {
1027             return false;
1028         } else {
1029             final PackageManager pm = getActivity().getPackageManager();
1030             final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1031             verification.setType(PACKAGE_MIME_TYPE);
1032             verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1033             final List<ResolveInfo> receivers = pm.queryBroadcastReceivers(verification, 0);
1034             if (receivers.size() == 0) {
1035                 return false;
1036             }
1037         }
1038         return true;
1039     }
1040
1041     private boolean showVerifierSetting() {
1042         return Settings.Global.getInt(getActivity().getContentResolver(),
1043                 Settings.Global.PACKAGE_VERIFIER_SETTING_VISIBLE, 1) > 0;
1044     }
1045
1046     private static boolean showEnableOemUnlockPreference() {
1047         return !SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals("");
1048     }
1049
1050     private static boolean showEnableMultiWindowPreference() {
1051         return !"user".equals(Build.TYPE);
1052     }
1053
1054     private void setEnableMultiWindow(boolean value) {
1055         SystemProperties.set(MULTI_WINDOW_SYSTEM_PROPERTY, String.valueOf(value));
1056         pokeSystemProperties();
1057     }
1058
1059     private void updateBugreportOptions() {
1060         final ComponentName bugreportStorageProviderComponentName =
1061                 new ComponentName("com.android.shell",
1062                         "com.android.shell.BugreportStorageProvider");
1063         if ("user".equals(Build.TYPE)) {
1064             final ContentResolver resolver = getActivity().getContentResolver();
1065             final boolean adbEnabled = Settings.Global.getInt(
1066                     resolver, Settings.Global.ADB_ENABLED, 0) != 0;
1067             if (adbEnabled) {
1068                 mBugreport.setEnabled(true);
1069                 mBugreportInPower.setEnabled(true);
1070                 getPackageManager().setComponentEnabledSetting(
1071                         bugreportStorageProviderComponentName,
1072                         PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0);
1073             } else {
1074                 mBugreport.setEnabled(false);
1075                 mBugreportInPower.setEnabled(false);
1076                 mBugreportInPower.setChecked(false);
1077                 Settings.Secure.putInt(resolver, Settings.Secure.BUGREPORT_IN_POWER_MENU, 0);
1078                 getPackageManager().setComponentEnabledSetting(
1079                         bugreportStorageProviderComponentName,
1080                         PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0);
1081             }
1082         } else {
1083             mBugreportInPower.setEnabled(true);
1084             getPackageManager().setComponentEnabledSetting(
1085                     bugreportStorageProviderComponentName,
1086                     PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0);
1087         }
1088     }
1089
1090     // Returns the current state of the system property that controls
1091     // strictmode flashes.  One of:
1092     //    0: not explicitly set one way or another
1093     //    1: on
1094     //    2: off
1095     private static int currentStrictModeActiveIndex() {
1096         if (TextUtils.isEmpty(SystemProperties.get(StrictMode.VISUAL_PROPERTY))) {
1097             return 0;
1098         }
1099         boolean enabled = SystemProperties.getBoolean(StrictMode.VISUAL_PROPERTY, false);
1100         return enabled ? 1 : 2;
1101     }
1102
1103     private void writeStrictModeVisualOptions() {
1104         try {
1105             mWindowManager.setStrictModeVisualIndicatorPreference(mStrictMode.isChecked()
1106                     ? "1" : "");
1107         } catch (RemoteException e) {
1108         }
1109     }
1110
1111     private void updateStrictModeVisualOptions() {
1112         updateSwitchPreference(mStrictMode, currentStrictModeActiveIndex() == 1);
1113     }
1114
1115     private void writePointerLocationOptions() {
1116         Settings.System.putInt(getActivity().getContentResolver(),
1117                 Settings.System.POINTER_LOCATION, mPointerLocation.isChecked() ? 1 : 0);
1118     }
1119
1120     private void updatePointerLocationOptions() {
1121         updateSwitchPreference(mPointerLocation,
1122                 Settings.System.getInt(getActivity().getContentResolver(),
1123                 Settings.System.POINTER_LOCATION, 0) != 0);
1124     }
1125
1126     private void writeShowTouchesOptions() {
1127         Settings.System.putInt(getActivity().getContentResolver(),
1128                 Settings.System.SHOW_TOUCHES, mShowTouches.isChecked() ? 1 : 0);
1129     }
1130
1131     private void updateShowTouchesOptions() {
1132         updateSwitchPreference(mShowTouches,
1133                 Settings.System.getInt(getActivity().getContentResolver(),
1134                 Settings.System.SHOW_TOUCHES, 0) != 0);
1135     }
1136
1137     private void updateFlingerOptions() {
1138         // magic communication with surface flinger.
1139         try {
1140             IBinder flinger = ServiceManager.getService("SurfaceFlinger");
1141             if (flinger != null) {
1142                 Parcel data = Parcel.obtain();
1143                 Parcel reply = Parcel.obtain();
1144                 data.writeInterfaceToken("android.ui.ISurfaceComposer");
1145                 flinger.transact(1010, data, reply, 0);
1146                 @SuppressWarnings("unused")
1147                 int showCpu = reply.readInt();
1148                 @SuppressWarnings("unused")
1149                 int enableGL = reply.readInt();
1150                 int showUpdates = reply.readInt();
1151                 updateSwitchPreference(mShowScreenUpdates, showUpdates != 0);
1152                 @SuppressWarnings("unused")
1153                 int showBackground = reply.readInt();
1154                 int disableOverlays = reply.readInt();
1155                 updateSwitchPreference(mDisableOverlays, disableOverlays != 0);
1156                 reply.recycle();
1157                 data.recycle();
1158             }
1159         } catch (RemoteException ex) {
1160         }
1161     }
1162
1163     private void writeShowUpdatesOption() {
1164         try {
1165             IBinder flinger = ServiceManager.getService("SurfaceFlinger");
1166             if (flinger != null) {
1167                 Parcel data = Parcel.obtain();
1168                 data.writeInterfaceToken("android.ui.ISurfaceComposer");
1169                 final int showUpdates = mShowScreenUpdates.isChecked() ? 1 : 0;
1170                 data.writeInt(showUpdates);
1171                 flinger.transact(1002, data, null, 0);
1172                 data.recycle();
1173
1174                 updateFlingerOptions();
1175             }
1176         } catch (RemoteException ex) {
1177         }
1178     }
1179
1180     private void writeDisableOverlaysOption() {
1181         try {
1182             IBinder flinger = ServiceManager.getService("SurfaceFlinger");
1183             if (flinger != null) {
1184                 Parcel data = Parcel.obtain();
1185                 data.writeInterfaceToken("android.ui.ISurfaceComposer");
1186                 final int disableOverlays = mDisableOverlays.isChecked() ? 1 : 0;
1187                 data.writeInt(disableOverlays);
1188                 flinger.transact(1008, data, null, 0);
1189                 data.recycle();
1190
1191                 updateFlingerOptions();
1192             }
1193         } catch (RemoteException ex) {
1194         }
1195     }
1196
1197     private void updateHardwareUiOptions() {
1198         updateSwitchPreference(mForceHardwareUi, SystemProperties.getBoolean(HARDWARE_UI_PROPERTY, false));
1199     }
1200
1201     private void writeHardwareUiOptions() {
1202         SystemProperties.set(HARDWARE_UI_PROPERTY, mForceHardwareUi.isChecked() ? "true" : "false");
1203         pokeSystemProperties();
1204     }
1205
1206     private void updateMsaaOptions() {
1207         updateSwitchPreference(mForceMsaa, SystemProperties.getBoolean(MSAA_PROPERTY, false));
1208     }
1209
1210     private void writeMsaaOptions() {
1211         SystemProperties.set(MSAA_PROPERTY, mForceMsaa.isChecked() ? "true" : "false");
1212         pokeSystemProperties();
1213     }
1214
1215     private void updateTrackFrameTimeOptions() {
1216         String value = SystemProperties.get(HardwareRenderer.PROFILE_PROPERTY);
1217         if (value == null) {
1218             value = "";
1219         }
1220
1221         CharSequence[] values = mTrackFrameTime.getEntryValues();
1222         for (int i = 0; i < values.length; i++) {
1223             if (value.contentEquals(values[i])) {
1224                 mTrackFrameTime.setValueIndex(i);
1225                 mTrackFrameTime.setSummary(mTrackFrameTime.getEntries()[i]);
1226                 return;
1227             }
1228         }
1229         mTrackFrameTime.setValueIndex(0);
1230         mTrackFrameTime.setSummary(mTrackFrameTime.getEntries()[0]);
1231     }
1232
1233     private void writeTrackFrameTimeOptions(Object newValue) {
1234         SystemProperties.set(HardwareRenderer.PROFILE_PROPERTY,
1235                 newValue == null ? "" : newValue.toString());
1236         pokeSystemProperties();
1237         updateTrackFrameTimeOptions();
1238     }
1239
1240     private void updateShowNonRectClipOptions() {
1241         String value = SystemProperties.get(
1242                 HardwareRenderer.DEBUG_SHOW_NON_RECTANGULAR_CLIP_PROPERTY);
1243         if (value == null) {
1244             value = "hide";
1245         }
1246
1247         CharSequence[] values = mShowNonRectClip.getEntryValues();
1248         for (int i = 0; i < values.length; i++) {
1249             if (value.contentEquals(values[i])) {
1250                 mShowNonRectClip.setValueIndex(i);
1251                 mShowNonRectClip.setSummary(mShowNonRectClip.getEntries()[i]);
1252                 return;
1253             }
1254         }
1255         mShowNonRectClip.setValueIndex(0);
1256         mShowNonRectClip.setSummary(mShowNonRectClip.getEntries()[0]);
1257     }
1258
1259     private void writeStayAwakeOptions(Object newValue) {
1260         int val = Integer.parseInt((String) newValue);
1261         Settings.Global.putInt(getActivity().getContentResolver(),
1262                     Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val);
1263         updateStayAwakeOptions();
1264     }
1265
1266     private void writeShowNonRectClipOptions(Object newValue) {
1267         SystemProperties.set(HardwareRenderer.DEBUG_SHOW_NON_RECTANGULAR_CLIP_PROPERTY,
1268                 newValue == null ? "" : newValue.toString());
1269         pokeSystemProperties();
1270         updateShowNonRectClipOptions();
1271     }
1272
1273     private void updateShowHwScreenUpdatesOptions() {
1274         updateSwitchPreference(mShowHwScreenUpdates,
1275                 SystemProperties.getBoolean(HardwareRenderer.DEBUG_DIRTY_REGIONS_PROPERTY, false));
1276     }
1277
1278     private void writeShowHwScreenUpdatesOptions() {
1279         SystemProperties.set(HardwareRenderer.DEBUG_DIRTY_REGIONS_PROPERTY,
1280                 mShowHwScreenUpdates.isChecked() ? "true" : null);
1281         pokeSystemProperties();
1282     }
1283
1284     private void updateShowHwLayersUpdatesOptions() {
1285         updateSwitchPreference(mShowHwLayersUpdates, SystemProperties.getBoolean(
1286                 HardwareRenderer.DEBUG_SHOW_LAYERS_UPDATES_PROPERTY, false));
1287     }
1288
1289     private void writeShowHwLayersUpdatesOptions() {
1290         SystemProperties.set(HardwareRenderer.DEBUG_SHOW_LAYERS_UPDATES_PROPERTY,
1291                 mShowHwLayersUpdates.isChecked() ? "true" : null);
1292         pokeSystemProperties();
1293     }
1294
1295     private void updateDebugHwOverdrawOptions() {
1296         String value = SystemProperties.get(HardwareRenderer.DEBUG_OVERDRAW_PROPERTY);
1297         if (value == null) {
1298             value = "";
1299         }
1300
1301         CharSequence[] values = mDebugHwOverdraw.getEntryValues();
1302         for (int i = 0; i < values.length; i++) {
1303             if (value.contentEquals(values[i])) {
1304                 mDebugHwOverdraw.setValueIndex(i);
1305                 mDebugHwOverdraw.setSummary(mDebugHwOverdraw.getEntries()[i]);
1306                 return;
1307             }
1308         }
1309         mDebugHwOverdraw.setValueIndex(0);
1310         mDebugHwOverdraw.setSummary(mDebugHwOverdraw.getEntries()[0]);
1311     }
1312
1313     private void writeDebugHwOverdrawOptions(Object newValue) {
1314         SystemProperties.set(HardwareRenderer.DEBUG_OVERDRAW_PROPERTY,
1315                 newValue == null ? "" : newValue.toString());
1316         pokeSystemProperties();
1317         updateDebugHwOverdrawOptions();
1318     }
1319
1320     private void updateDebugLayoutOptions() {
1321         updateSwitchPreference(mDebugLayout,
1322                 SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false));
1323     }
1324
1325     private void writeDebugLayoutOptions() {
1326         SystemProperties.set(View.DEBUG_LAYOUT_PROPERTY,
1327                 mDebugLayout.isChecked() ? "true" : "false");
1328         pokeSystemProperties();
1329     }
1330
1331     private void updateSimulateColorSpace() {
1332         final ContentResolver cr = getContentResolver();
1333         final boolean enabled = Settings.Secure.getInt(
1334                 cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 0) != 0;
1335         if (enabled) {
1336             final String mode = Integer.toString(Settings.Secure.getInt(
1337                     cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER,
1338                     AccessibilityManager.DALTONIZER_DISABLED));
1339             mSimulateColorSpace.setValue(mode);
1340             final int index = mSimulateColorSpace.findIndexOfValue(mode);
1341             if (index < 0) {
1342                 // We're using a mode controlled by accessibility preferences.
1343                 mSimulateColorSpace.setSummary(getString(R.string.daltonizer_type_overridden,
1344                         getString(R.string.accessibility_display_daltonizer_preference_title)));
1345             } else {
1346                 mSimulateColorSpace.setSummary("%s");
1347             }
1348         } else {
1349             mSimulateColorSpace.setValue(
1350                     Integer.toString(AccessibilityManager.DALTONIZER_DISABLED));
1351         }
1352     }
1353
1354     /**
1355      * @return <code>true</code> if the color space preference is currently
1356      *         controlled by development settings
1357      */
1358     private boolean usingDevelopmentColorSpace() {
1359         final ContentResolver cr = getContentResolver();
1360         final boolean enabled = Settings.Secure.getInt(
1361                 cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 0) != 0;
1362         if (enabled) {
1363             final String mode = Integer.toString(Settings.Secure.getInt(
1364                     cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER,
1365                     AccessibilityManager.DALTONIZER_DISABLED));
1366             final int index = mSimulateColorSpace.findIndexOfValue(mode);
1367             if (index >= 0) {
1368                 // We're using a mode controlled by developer preferences.
1369                 return true;
1370             }
1371         }
1372         return false;
1373     }
1374
1375     private void writeSimulateColorSpace(Object value) {
1376         final ContentResolver cr = getContentResolver();
1377         final int newMode = Integer.parseInt(value.toString());
1378         if (newMode < 0) {
1379             Settings.Secure.putInt(cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 0);
1380         } else {
1381             Settings.Secure.putInt(cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 1);
1382             Settings.Secure.putInt(cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER, newMode);
1383         }
1384     }
1385
1386     private void updateUSBAudioOptions() {
1387         updateSwitchPreference(mUSBAudio, Settings.Secure.getInt(getContentResolver(),
1388                 Settings.Secure.USB_AUDIO_AUTOMATIC_ROUTING_DISABLED, 0) != 0);
1389     }
1390
1391     private void writeUSBAudioOptions() {
1392         Settings.Secure.putInt(getContentResolver(),
1393                 Settings.Secure.USB_AUDIO_AUTOMATIC_ROUTING_DISABLED,
1394                 mUSBAudio.isChecked() ? 1 : 0);
1395     }
1396
1397     private void updateForceRtlOptions() {
1398         updateSwitchPreference(mForceRtlLayout,
1399                 Settings.Global.getInt(getActivity().getContentResolver(),
1400                 Settings.Global.DEVELOPMENT_FORCE_RTL, 0) != 0);
1401     }
1402
1403     private void writeForceRtlOptions() {
1404         boolean value = mForceRtlLayout.isChecked();
1405         Settings.Global.putInt(getActivity().getContentResolver(),
1406                 Settings.Global.DEVELOPMENT_FORCE_RTL, value ? 1 : 0);
1407         SystemProperties.set(Settings.Global.DEVELOPMENT_FORCE_RTL, value ? "1" : "0");
1408         LocalePicker.updateLocale(getActivity().getResources().getConfiguration().locale);
1409     }
1410
1411     private void updateWifiDisplayCertificationOptions() {
1412         updateSwitchPreference(mWifiDisplayCertification, Settings.Global.getInt(
1413                 getActivity().getContentResolver(),
1414                 Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON, 0) != 0);
1415     }
1416
1417     private void writeWifiDisplayCertificationOptions() {
1418         Settings.Global.putInt(getActivity().getContentResolver(),
1419                 Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON,
1420                 mWifiDisplayCertification.isChecked() ? 1 : 0);
1421     }
1422
1423     private void updateWifiVerboseLoggingOptions() {
1424         boolean enabled = mWifiManager.getVerboseLoggingLevel() > 0;
1425         updateSwitchPreference(mWifiVerboseLogging, enabled);
1426     }
1427
1428     private void writeWifiVerboseLoggingOptions() {
1429         mWifiManager.enableVerboseLogging(mWifiVerboseLogging.isChecked() ? 1 : 0);
1430     }
1431
1432     private void updateWifiAggressiveHandoverOptions() {
1433         boolean enabled = mWifiManager.getAggressiveHandover() > 0;
1434         updateSwitchPreference(mWifiAggressiveHandover, enabled);
1435     }
1436
1437     private void writeWifiAggressiveHandoverOptions() {
1438         mWifiManager.enableAggressiveHandover(mWifiAggressiveHandover.isChecked() ? 1 : 0);
1439     }
1440
1441     private void updateWifiAllowScansWithTrafficOptions() {
1442         boolean enabled = mWifiManager.getAllowScansWithTraffic() > 0;
1443         updateSwitchPreference(mWifiAllowScansWithTraffic, enabled);
1444     }
1445
1446     private void writeWifiAllowScansWithTrafficOptions() {
1447         mWifiManager.setAllowScansWithTraffic(mWifiAllowScansWithTraffic.isChecked() ? 1 : 0);
1448     }
1449
1450     private void updateLegacyDhcpClientOptions() {
1451         updateSwitchPreference(mLegacyDhcpClient, Settings.Global.getInt(
1452                 getActivity().getContentResolver(),
1453                 Settings.Global.LEGACY_DHCP_CLIENT, 0) != 0);
1454     }
1455
1456     private void writeLegacyDhcpClientOptions() {
1457         Settings.Global.putInt(getActivity().getContentResolver(),
1458                 Settings.Global.LEGACY_DHCP_CLIENT,
1459                 mLegacyDhcpClient.isChecked() ? 1 : 0);
1460     }
1461
1462     private void updateMobileDataAlwaysOnOptions() {
1463         updateSwitchPreference(mMobileDataAlwaysOn, Settings.Global.getInt(
1464                 getActivity().getContentResolver(),
1465                 Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) != 0);
1466     }
1467
1468     private void writeMobileDataAlwaysOnOptions() {
1469         Settings.Global.putInt(getActivity().getContentResolver(),
1470                 Settings.Global.MOBILE_DATA_ALWAYS_ON,
1471                 mMobileDataAlwaysOn.isChecked() ? 1 : 0);
1472     }
1473
1474     private void updateLogdSizeValues() {
1475         if (mLogdSize != null) {
1476             String currentValue = SystemProperties.get(SELECT_LOGD_SIZE_PROPERTY);
1477             if (currentValue == null) {
1478                 currentValue = SystemProperties.get(SELECT_LOGD_DEFAULT_SIZE_PROPERTY);
1479                 if (currentValue == null) {
1480                     currentValue = "256K";
1481                 }
1482             }
1483             String[] values = getResources().getStringArray(R.array.select_logd_size_values);
1484             String[] titles = getResources().getStringArray(R.array.select_logd_size_titles);
1485             if (SystemProperties.get("ro.config.low_ram").equals("true")) {
1486                 mLogdSize.setEntries(R.array.select_logd_size_lowram_titles);
1487                 titles = getResources().getStringArray(R.array.select_logd_size_lowram_titles);
1488             }
1489             String[] summaries = getResources().getStringArray(R.array.select_logd_size_summaries);
1490             int index = 1; // punt to second entry if not found
1491             for (int i = 0; i < titles.length; i++) {
1492                 if (currentValue.equals(values[i])
1493                         || currentValue.equals(titles[i])) {
1494                     index = i;
1495                     break;
1496                 }
1497             }
1498             mLogdSize.setValue(values[index]);
1499             mLogdSize.setSummary(summaries[index]);
1500             mLogdSize.setOnPreferenceChangeListener(this);
1501         }
1502     }
1503
1504     private void writeLogdSizeOption(Object newValue) {
1505         String currentValue = SystemProperties.get(SELECT_LOGD_DEFAULT_SIZE_PROPERTY);
1506         if (currentValue != null) {
1507             DEFAULT_LOG_RING_BUFFER_SIZE_IN_BYTES = currentValue;
1508         }
1509         final String size = (newValue != null) ?
1510                 newValue.toString() : DEFAULT_LOG_RING_BUFFER_SIZE_IN_BYTES;
1511         SystemProperties.set(SELECT_LOGD_SIZE_PROPERTY, size);
1512         pokeSystemProperties();
1513         try {
1514             Process p = Runtime.getRuntime().exec("logcat -b all -G " + size);
1515             p.waitFor();
1516             Log.i(TAG, "Logcat ring buffer sizes set to: " + size);
1517         } catch (Exception e) {
1518             Log.w(TAG, "Cannot set logcat ring buffer sizes", e);
1519         }
1520         updateLogdSizeValues();
1521     }
1522
1523     private void updateUsbConfigurationValues() {
1524         if (mUsbConfiguration != null) {
1525             UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
1526
1527             String[] values = getResources().getStringArray(R.array.usb_configuration_values);
1528             String[] titles = getResources().getStringArray(R.array.usb_configuration_titles);
1529             int index = 0;
1530             for (int i = 0; i < titles.length; i++) {
1531                 if (manager.isFunctionEnabled(values[i])) {
1532                     index = i;
1533                     break;
1534                 }
1535             }
1536             mUsbConfiguration.setValue(values[index]);
1537             mUsbConfiguration.setSummary(titles[index]);
1538             mUsbConfiguration.setOnPreferenceChangeListener(this);
1539         }
1540     }
1541
1542     private void writeUsbConfigurationOption(Object newValue) {
1543         UsbManager manager = (UsbManager)getActivity().getSystemService(Context.USB_SERVICE);
1544         String function = newValue.toString();
1545         manager.setCurrentFunction(function);
1546         if (function.equals("none")) {
1547             manager.setUsbDataUnlocked(false);
1548         } else {
1549             manager.setUsbDataUnlocked(true);
1550         }
1551     }
1552
1553     private void updateCpuUsageOptions() {
1554         updateSwitchPreference(mShowCpuUsage,
1555                 Settings.Global.getInt(getActivity().getContentResolver(),
1556                 Settings.Global.SHOW_PROCESSES, 0) != 0);
1557     }
1558
1559     private void writeCpuUsageOptions() {
1560         boolean value = mShowCpuUsage.isChecked();
1561         Settings.Global.putInt(getActivity().getContentResolver(),
1562                 Settings.Global.SHOW_PROCESSES, value ? 1 : 0);
1563         Intent service = (new Intent())
1564                 .setClassName("com.android.systemui", "com.android.systemui.LoadAverageService");
1565         if (value) {
1566             getActivity().startService(service);
1567         } else {
1568             getActivity().stopService(service);
1569         }
1570     }
1571
1572     private void writeImmediatelyDestroyActivitiesOptions() {
1573         try {
1574             ActivityManagerNative.getDefault().setAlwaysFinish(
1575                     mImmediatelyDestroyActivities.isChecked());
1576         } catch (RemoteException ex) {
1577         }
1578     }
1579
1580     private void updateImmediatelyDestroyActivitiesOptions() {
1581         updateSwitchPreference(mImmediatelyDestroyActivities, Settings.Global.getInt(
1582                 getActivity().getContentResolver(), Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0);
1583     }
1584
1585     private void updateAnimationScaleValue(int which, ListPreference pref) {
1586         try {
1587             float scale = mWindowManager.getAnimationScale(which);
1588             if (scale != 1) {
1589                 mHaveDebugSettings = true;
1590             }
1591             CharSequence[] values = pref.getEntryValues();
1592             for (int i=0; i<values.length; i++) {
1593                 float val = Float.parseFloat(values[i].toString());
1594                 if (scale <= val) {
1595                     pref.setValueIndex(i);
1596                     pref.setSummary(pref.getEntries()[i]);
1597                     return;
1598                 }
1599             }
1600             pref.setValueIndex(values.length-1);
1601             pref.setSummary(pref.getEntries()[0]);
1602         } catch (RemoteException e) {
1603         }
1604     }
1605
1606     private void updateAnimationScaleOptions() {
1607         updateAnimationScaleValue(0, mWindowAnimationScale);
1608         updateAnimationScaleValue(1, mTransitionAnimationScale);
1609         updateAnimationScaleValue(2, mAnimatorDurationScale);
1610     }
1611
1612     private void writeAnimationScaleOption(int which, ListPreference pref, Object newValue) {
1613         try {
1614             float scale = newValue != null ? Float.parseFloat(newValue.toString()) : 1;
1615             mWindowManager.setAnimationScale(which, scale);
1616             updateAnimationScaleValue(which, pref);
1617         } catch (RemoteException e) {
1618         }
1619     }
1620
1621     private void updateOverlayDisplayDevicesOptions() {
1622         String value = Settings.Global.getString(getActivity().getContentResolver(),
1623                 Settings.Global.OVERLAY_DISPLAY_DEVICES);
1624         if (value == null) {
1625             value = "";
1626         }
1627
1628         CharSequence[] values = mOverlayDisplayDevices.getEntryValues();
1629         for (int i = 0; i < values.length; i++) {
1630             if (value.contentEquals(values[i])) {
1631                 mOverlayDisplayDevices.setValueIndex(i);
1632                 mOverlayDisplayDevices.setSummary(mOverlayDisplayDevices.getEntries()[i]);
1633                 return;
1634             }
1635         }
1636         mOverlayDisplayDevices.setValueIndex(0);
1637         mOverlayDisplayDevices.setSummary(mOverlayDisplayDevices.getEntries()[0]);
1638     }
1639
1640     private void writeOverlayDisplayDevicesOptions(Object newValue) {
1641         Settings.Global.putString(getActivity().getContentResolver(),
1642                 Settings.Global.OVERLAY_DISPLAY_DEVICES, (String)newValue);
1643         updateOverlayDisplayDevicesOptions();
1644     }
1645
1646     private void updateOpenGLTracesOptions() {
1647         String value = SystemProperties.get(OPENGL_TRACES_PROPERTY);
1648         if (value == null) {
1649             value = "";
1650         }
1651
1652         CharSequence[] values = mOpenGLTraces.getEntryValues();
1653         for (int i = 0; i < values.length; i++) {
1654             if (value.contentEquals(values[i])) {
1655                 mOpenGLTraces.setValueIndex(i);
1656                 mOpenGLTraces.setSummary(mOpenGLTraces.getEntries()[i]);
1657                 return;
1658             }
1659         }
1660         mOpenGLTraces.setValueIndex(0);
1661         mOpenGLTraces.setSummary(mOpenGLTraces.getEntries()[0]);
1662     }
1663
1664     private void writeOpenGLTracesOptions(Object newValue) {
1665         SystemProperties.set(OPENGL_TRACES_PROPERTY, newValue == null ? "" : newValue.toString());
1666         pokeSystemProperties();
1667         updateOpenGLTracesOptions();
1668     }
1669
1670     private void updateAppProcessLimitOptions() {
1671         try {
1672             int limit = ActivityManagerNative.getDefault().getProcessLimit();
1673             CharSequence[] values = mAppProcessLimit.getEntryValues();
1674             for (int i=0; i<values.length; i++) {
1675                 int val = Integer.parseInt(values[i].toString());
1676                 if (val >= limit) {
1677                     if (i != 0) {
1678                         mHaveDebugSettings = true;
1679                     }
1680                     mAppProcessLimit.setValueIndex(i);
1681                     mAppProcessLimit.setSummary(mAppProcessLimit.getEntries()[i]);
1682                     return;
1683                 }
1684             }
1685             mAppProcessLimit.setValueIndex(0);
1686             mAppProcessLimit.setSummary(mAppProcessLimit.getEntries()[0]);
1687         } catch (RemoteException e) {
1688         }
1689     }
1690
1691     private void writeAppProcessLimitOptions(Object newValue) {
1692         try {
1693             int limit = newValue != null ? Integer.parseInt(newValue.toString()) : -1;
1694             ActivityManagerNative.getDefault().setProcessLimit(limit);
1695             updateAppProcessLimitOptions();
1696         } catch (RemoteException e) {
1697         }
1698     }
1699
1700     private void writeShowAllANRsOptions() {
1701         Settings.Secure.putInt(getActivity().getContentResolver(),
1702                 Settings.Secure.ANR_SHOW_BACKGROUND,
1703                 mShowAllANRs.isChecked() ? 1 : 0);
1704     }
1705
1706     private void updateShowAllANRsOptions() {
1707         updateSwitchPreference(mShowAllANRs, Settings.Secure.getInt(
1708                 getActivity().getContentResolver(), Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0);
1709     }
1710
1711     private void confirmEnableOemUnlock() {
1712         DialogInterface.OnClickListener onConfirmListener = new DialogInterface.OnClickListener() {
1713             @Override
1714             public void onClick(DialogInterface dialog, int which) {
1715                 Utils.setOemUnlockEnabled(getActivity(), true);
1716                 updateAllOptions();
1717             }
1718         };
1719
1720         new AlertDialog.Builder(getActivity())
1721                 .setTitle(R.string.confirm_enable_oem_unlock_title)
1722                 .setMessage(R.string.confirm_enable_oem_unlock_text)
1723                 .setPositiveButton(R.string.enable_text, onConfirmListener)
1724                 .setNegativeButton(android.R.string.cancel, null)
1725                 .create()
1726                 .show();
1727     }
1728
1729     private void confirmEnableMultiWindowMode() {
1730         DialogInterface.OnClickListener onConfirmListener = new DialogInterface.OnClickListener() {
1731             @Override
1732             public void onClick(DialogInterface dialog, int which) {
1733                 setEnableMultiWindow((which == DialogInterface.BUTTON_POSITIVE) ? true : false);
1734                 updateAllOptions();
1735             }
1736         };
1737
1738         new AlertDialog.Builder(getActivity())
1739                 .setTitle(R.string.confirm_enable_multi_window_title)
1740                 .setMessage(R.string.confirm_enable_multi_window_text)
1741                 .setPositiveButton(R.string.enable_text, onConfirmListener)
1742                 .setNegativeButton(android.R.string.cancel, onConfirmListener)
1743                 .create()
1744                 .show();
1745     }
1746
1747     private void updateUpdateRecoveryOptions() {
1748         updateSwitchPreference(mUpdateRecovery, SystemProperties.getBoolean(
1749                 UPDATE_RECOVERY_PROPERTY, false));
1750     }
1751
1752     private void writeUpdateRecoveryOptions() {
1753         SystemProperties.set(UPDATE_RECOVERY_PROPERTY,
1754                 mUpdateRecovery.isChecked() ? "true" : "false");
1755         pokeSystemProperties();
1756     }
1757
1758     private void resetUpdateRecoveryOptions() {
1759         // User builds should update recovery by default
1760         if ("user".equals(Build.TYPE)) {
1761             SystemProperties.set(UPDATE_RECOVERY_PROPERTY, "true");
1762         }
1763     }
1764
1765     @Override
1766     public void onSwitchChanged(Switch switchView, boolean isChecked) {
1767         if (switchView != mSwitchBar.getSwitch()) {
1768             return;
1769         }
1770         if (isChecked != mLastEnabledState) {
1771             if (isChecked) {
1772                 mDialogClicked = false;
1773                 if (mEnableDialog != null) {
1774                     dismissDialogs();
1775                 }
1776                 mEnableDialog = new AlertDialog.Builder(getActivity()).setMessage(
1777                         getActivity().getResources().getString(
1778                                 R.string.dev_settings_warning_message))
1779                         .setTitle(R.string.dev_settings_warning_title)
1780                         .setPositiveButton(android.R.string.yes, this)
1781                         .setNegativeButton(android.R.string.no, this)
1782                         .show();
1783                 mEnableDialog.setOnDismissListener(this);
1784             } else {
1785                 resetDangerousOptions();
1786                 Settings.Global.putInt(getActivity().getContentResolver(),
1787                         Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0);
1788                 mLastEnabledState = isChecked;
1789                 setPrefsEnabledState(mLastEnabledState);
1790
1791                 // Hide development settings from the Settings menu (Android 4.2 behaviour)
1792                 getActivity().getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE).edit()
1793                     .putBoolean(PREF_SHOW, false)
1794                     .apply();
1795             }
1796         }
1797     }
1798
1799     @Override
1800     public void onActivityResult(int requestCode, int resultCode, Intent data) {
1801         if (requestCode == RESULT_DEBUG_APP) {
1802             if (resultCode == Activity.RESULT_OK) {
1803                 mDebugApp = data.getAction();
1804                 writeDebuggerOptions();
1805                 updateDebuggerOptions();
1806             }
1807         } else if (requestCode == RESULT_MOCK_LOCATION_APP) {
1808             if (resultCode == Activity.RESULT_OK) {
1809                 mMockLocationApp = data.getAction();
1810                 writeMockLocation();
1811                 updateMockLocation();
1812             }
1813         } else if (requestCode == REQUEST_CODE_ENABLE_OEM_UNLOCK) {
1814             if (resultCode == Activity.RESULT_OK) {
1815                 if (mEnableOemUnlock.isChecked()) {
1816                     confirmEnableOemUnlock();
1817                 } else {
1818                     Utils.setOemUnlockEnabled(getActivity(), false);
1819                 }
1820             }
1821         } else {
1822             super.onActivityResult(requestCode, resultCode, data);
1823         }
1824     }
1825
1826     @Override
1827     public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
1828         if (Utils.isMonkeyRunning()) {
1829             return false;
1830         }
1831
1832         if (preference == mEnableAdb) {
1833             if (mEnableAdb.isChecked()) {
1834                 mDialogClicked = false;
1835                 if (mAdbDialog != null) {
1836                     dismissDialogs();
1837                 }
1838                 mAdbDialog = new AlertDialog.Builder(getActivity()).setMessage(
1839                         getActivity().getResources().getString(R.string.adb_warning_message))
1840                         .setTitle(R.string.adb_warning_title)
1841                         .setPositiveButton(android.R.string.yes, this)
1842                         .setNegativeButton(android.R.string.no, this)
1843                         .show();
1844                 mAdbDialog.setOnDismissListener(this);
1845             } else {
1846                 Settings.Global.putInt(getActivity().getContentResolver(),
1847                         Settings.Global.ADB_ENABLED, 0);
1848                 mVerifyAppsOverUsb.setEnabled(false);
1849                 mVerifyAppsOverUsb.setChecked(false);
1850                 updateBugreportOptions();
1851             }
1852         } else if (preference == mAdbNotify) {
1853             CMSettings.Secure.putInt(getActivity().getContentResolver(),
1854                     CMSettings.Secure.ADB_NOTIFY,
1855                     mAdbNotify.isChecked() ? 1 : 0);
1856         } else if (preference == mAdbOverNetwork) {
1857             if (mAdbOverNetwork.isChecked()) {
1858                 if (mAdbTcpDialog != null) {
1859                     dismissDialogs();
1860                 }
1861                 mAdbTcpDialog = new AlertDialog.Builder(getActivity()).setMessage(
1862                         getResources().getString(R.string.adb_over_network_warning))
1863                         .setTitle(R.string.adb_over_network)
1864                         .setPositiveButton(android.R.string.yes, this)
1865                         .setNegativeButton(android.R.string.no, this)
1866                         .show();
1867                 mAdbTcpDialog.setOnDismissListener(this);
1868             } else {
1869                 CMSettings.Secure.putInt(getActivity().getContentResolver(),
1870                         CMSettings.Secure.ADB_PORT, -1);
1871                 updateAdbOverNetwork();
1872             }
1873         } else if (preference == mClearAdbKeys) {
1874             if (mAdbKeysDialog != null) dismissDialogs();
1875             mAdbKeysDialog = new AlertDialog.Builder(getActivity())
1876                         .setMessage(R.string.adb_keys_warning_message)
1877                         .setPositiveButton(android.R.string.ok, this)
1878                         .setNegativeButton(android.R.string.cancel, null)
1879                         .show();
1880         } else if (preference == mEnableTerminal) {
1881             final PackageManager pm = getActivity().getPackageManager();
1882             pm.setApplicationEnabledSetting(TERMINAL_APP_PACKAGE,
1883                     mEnableTerminal.isChecked() ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
1884                             : PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0);
1885         } else if (preference == mBugreportInPower) {
1886             Settings.Secure.putInt(getActivity().getContentResolver(),
1887                     Settings.Secure.BUGREPORT_IN_POWER_MENU,
1888                     mBugreportInPower.isChecked() ? 1 : 0);
1889         } else if (preference == mBtHciSnoopLog) {
1890             writeBtHciSnoopLogOptions();
1891         } else if (preference == mEnableOemUnlock) {
1892             if (!showKeyguardConfirmation(getResources(), REQUEST_CODE_ENABLE_OEM_UNLOCK)) {
1893                 if (mEnableOemUnlock.isChecked()) {
1894                     confirmEnableOemUnlock();
1895                 } else {
1896                     Utils.setOemUnlockEnabled(getActivity(), false);
1897                 }
1898             }
1899         } else if (preference == mMockLocationAppPref) {
1900             Intent intent = new Intent(getActivity(), AppPicker.class);
1901             intent.putExtra(AppPicker.EXTRA_REQUESTIING_PERMISSION,
1902                     Manifest.permission.ACCESS_MOCK_LOCATION);
1903             startActivityForResult(intent, RESULT_MOCK_LOCATION_APP);
1904         } else if (preference == mDebugViewAttributes) {
1905             Settings.Global.putInt(getActivity().getContentResolver(),
1906                     Settings.Global.DEBUG_VIEW_ATTRIBUTES,
1907                     mDebugViewAttributes.isChecked() ? 1 : 0);
1908         } else if (preference == mDebugAppPref) {
1909             Intent intent = new Intent(getActivity(), AppPicker.class);
1910             intent.putExtra(AppPicker.EXTRA_DEBUGGABLE, true);
1911             startActivityForResult(intent, RESULT_DEBUG_APP);
1912         } else if (preference == mWaitForDebugger) {
1913             writeDebuggerOptions();
1914         } else if (preference == mVerifyAppsOverUsb) {
1915             writeVerifyAppsOverUsbOptions();
1916         } else if (preference == mStrictMode) {
1917             writeStrictModeVisualOptions();
1918         } else if (preference == mPointerLocation) {
1919             writePointerLocationOptions();
1920         } else if (preference == mShowTouches) {
1921             writeShowTouchesOptions();
1922         } else if (preference == mShowScreenUpdates) {
1923             writeShowUpdatesOption();
1924         } else if (preference == mDisableOverlays) {
1925             writeDisableOverlaysOption();
1926         } else if (preference == mEnableMultiWindow) {
1927             if (mEnableMultiWindow.isChecked()) {
1928                 confirmEnableMultiWindowMode();
1929             } else {
1930                 setEnableMultiWindow(false);
1931             }
1932         } else if (preference == mShowCpuUsage) {
1933             writeCpuUsageOptions();
1934         } else if (preference == mImmediatelyDestroyActivities) {
1935             writeImmediatelyDestroyActivitiesOptions();
1936         } else if (preference == mShowAllANRs) {
1937             writeShowAllANRsOptions();
1938         } else if (preference == mForceHardwareUi) {
1939             writeHardwareUiOptions();
1940         } else if (preference == mForceMsaa) {
1941             writeMsaaOptions();
1942         } else if (preference == mShowHwScreenUpdates) {
1943             writeShowHwScreenUpdatesOptions();
1944         } else if (preference == mShowHwLayersUpdates) {
1945             writeShowHwLayersUpdatesOptions();
1946         } else if (preference == mDebugLayout) {
1947             writeDebugLayoutOptions();
1948         } else if (preference == mForceRtlLayout) {
1949             writeForceRtlOptions();
1950         } else if (preference == mWifiDisplayCertification) {
1951             writeWifiDisplayCertificationOptions();
1952         } else if (preference == mWifiVerboseLogging) {
1953             writeWifiVerboseLoggingOptions();
1954         } else if (preference == mWifiAggressiveHandover) {
1955             writeWifiAggressiveHandoverOptions();
1956         } else if (preference == mWifiAllowScansWithTraffic) {
1957             writeWifiAllowScansWithTrafficOptions();
1958         } else if (preference == mLegacyDhcpClient) {
1959             writeLegacyDhcpClientOptions();
1960         } else if (preference == mMobileDataAlwaysOn) {
1961             writeMobileDataAlwaysOnOptions();
1962         } else if (preference == mUSBAudio) {
1963             writeUSBAudioOptions();
1964         } else if (preference == mAdvancedReboot) {
1965             writeAdvancedRebootOptions();
1966         } else if (INACTIVE_APPS_KEY.equals(preference.getKey())) {
1967             startInactiveAppsFragment();
1968         } else if (preference == mDevelopmentShortcut) {
1969             writeDevelopmentShortcutOptions();
1970         } else if (preference == mKillAppLongpressBack) {
1971             writeKillAppLongpressBackOptions();
1972         } else if (preference == mUpdateRecovery) {
1973             if (mSwitchBar.isChecked()) {
1974                 if (mUpdateRecoveryDialog != null) {
1975                     dismissDialogs();
1976                 }
1977                 if (mUpdateRecovery.isChecked()) {
1978                     mUpdateRecoveryDialog = new AlertDialog.Builder(getActivity()).setMessage(
1979                             getResources().getString(R.string.update_recovery_on_warning))
1980                             .setTitle(R.string.update_recovery_title)
1981                             .setPositiveButton(android.R.string.yes, this)
1982                             .setNegativeButton(android.R.string.no, this)
1983                             .show();
1984                 } else {
1985                     mUpdateRecoveryDialog = new AlertDialog.Builder(getActivity()).setMessage(
1986                             getResources().getString(R.string.update_recovery_off_warning))
1987                             .setTitle(R.string.update_recovery_title)
1988                             .setPositiveButton(android.R.string.yes, this)
1989                             .setNegativeButton(android.R.string.no, this)
1990                             .show();
1991                 }
1992                 mUpdateRecoveryDialog.setOnDismissListener(this);
1993             }
1994         } else {
1995             return super.onPreferenceTreeClick(preferenceScreen, preference);
1996         }
1997
1998         return false;
1999     }
2000
2001     private void startInactiveAppsFragment() {
2002         ((SettingsActivity) getActivity()).startPreferencePanel(
2003                 InactiveApps.class.getName(),
2004                 null, R.string.inactive_apps_title, null, null, 0);
2005     }
2006
2007     private boolean showKeyguardConfirmation(Resources resources, int requestCode) {
2008         return new ChooseLockSettingsHelper(getActivity(), this).launchConfirmationActivity(
2009                 requestCode, resources.getString(R.string.oem_unlock_enable));
2010     }
2011
2012     @Override
2013     public boolean onPreferenceChange(Preference preference, Object newValue) {
2014         if (HDCP_CHECKING_KEY.equals(preference.getKey())) {
2015             SystemProperties.set(HDCP_CHECKING_PROPERTY, newValue.toString());
2016             updateHdcpValues();
2017             pokeSystemProperties();
2018             return true;
2019         } else if (preference == mLogdSize) {
2020             writeLogdSizeOption(newValue);
2021             return true;
2022         } else if (preference == mUsbConfiguration) {
2023             writeUsbConfigurationOption(newValue);
2024             return true;
2025         } else if (preference == mWindowAnimationScale) {
2026             writeAnimationScaleOption(0, mWindowAnimationScale, newValue);
2027             return true;
2028         } else if (preference == mTransitionAnimationScale) {
2029             writeAnimationScaleOption(1, mTransitionAnimationScale, newValue);
2030             return true;
2031         } else if (preference == mAnimatorDurationScale) {
2032             writeAnimationScaleOption(2, mAnimatorDurationScale, newValue);
2033             return true;
2034         } else if (preference == mOverlayDisplayDevices) {
2035             writeOverlayDisplayDevicesOptions(newValue);
2036             return true;
2037         } else if (preference == mOpenGLTraces) {
2038             writeOpenGLTracesOptions(newValue);
2039             return true;
2040         } else if (preference == mTrackFrameTime) {
2041             writeTrackFrameTimeOptions(newValue);
2042             return true;
2043         } else if (preference == mDebugHwOverdraw) {
2044             writeDebugHwOverdrawOptions(newValue);
2045             return true;
2046         } else if (preference == mShowNonRectClip) {
2047             writeShowNonRectClipOptions(newValue);
2048             return true;
2049         } else if (preference == mAppProcessLimit) {
2050             writeAppProcessLimitOptions(newValue);
2051             return true;
2052         } else if (preference == mSimulateColorSpace) {
2053             writeSimulateColorSpace(newValue);
2054             return true;
2055         } else if (preference == mRootAccess) {
2056             if ("0".equals(SystemProperties.get(ROOT_ACCESS_PROPERTY, "0"))
2057                     && !"0".equals(newValue)) {
2058                 mSelectedRootValue = newValue;
2059                 mDialogClicked = false;
2060                 if (mRootDialog != null) {
2061                     dismissDialogs();
2062                 }
2063                 mRootDialog = new AlertDialog.Builder(getActivity())
2064                         .setMessage(getResources().getString(R.string.root_access_warning_message))
2065                         .setTitle(R.string.root_access_warning_title)
2066                         .setPositiveButton(android.R.string.yes, this)
2067                         .setNegativeButton(android.R.string.no, this).show();
2068                 mRootDialog.setOnDismissListener(this);
2069             } else {
2070                 writeRootAccessOptions(newValue);
2071             }
2072             return true;
2073         } else if (preference == mKeepScreenOn) {
2074             writeStayAwakeOptions(newValue);
2075             return true;
2076         }
2077         return false;
2078     }
2079
2080     private void dismissDialogs() {
2081         if (mAdbDialog != null) {
2082             mAdbDialog.dismiss();
2083             mAdbDialog = null;
2084         }
2085         if (mAdbTcpDialog != null) {
2086             mAdbTcpDialog.dismiss();
2087             mAdbTcpDialog = null;
2088         }
2089         if (mAdbKeysDialog != null) {
2090             mAdbKeysDialog.dismiss();
2091             mAdbKeysDialog = null;
2092         }
2093         if (mEnableDialog != null) {
2094             mEnableDialog.dismiss();
2095             mEnableDialog = null;
2096         }
2097         if (mRootDialog != null) {
2098             mRootDialog.dismiss();
2099             mRootDialog = null;
2100         }
2101         if (mUpdateRecoveryDialog != null) {
2102             mUpdateRecoveryDialog.dismiss();
2103             mUpdateRecoveryDialog = null;
2104         }
2105     }
2106
2107     public void onClick(DialogInterface dialog, int which) {
2108         if (dialog == mAdbDialog) {
2109             if (which == DialogInterface.BUTTON_POSITIVE) {
2110                 mDialogClicked = true;
2111                 Settings.Global.putInt(getActivity().getContentResolver(),
2112                         Settings.Global.ADB_ENABLED, 1);
2113                 mVerifyAppsOverUsb.setEnabled(true);
2114                 updateVerifyAppsOverUsbOptions();
2115                 updateBugreportOptions();
2116             }
2117         } else if (dialog == mAdbTcpDialog) {
2118             if (which == DialogInterface.BUTTON_POSITIVE) {
2119                 CMSettings.Secure.putInt(getActivity().getContentResolver(),
2120                         CMSettings.Secure.ADB_PORT, 5555);
2121             }
2122         } else if (dialog == mAdbKeysDialog) {
2123             if (which == DialogInterface.BUTTON_POSITIVE) {
2124                 try {
2125                     IBinder b = ServiceManager.getService(Context.USB_SERVICE);
2126                     IUsbManager service = IUsbManager.Stub.asInterface(b);
2127                     service.clearUsbDebuggingKeys();
2128                 } catch (RemoteException e) {
2129                     Log.e(TAG, "Unable to clear adb keys", e);
2130                 }
2131             }
2132         } else if (dialog == mEnableDialog) {
2133             if (which == DialogInterface.BUTTON_POSITIVE) {
2134                 mDialogClicked = true;
2135                 Settings.Global.putInt(getActivity().getContentResolver(),
2136                         Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 1);
2137                 mLastEnabledState = true;
2138                 setPrefsEnabledState(mLastEnabledState);
2139
2140                 // Make sure the development settings is visible in the main Settings menu
2141                 // This is needed since we may have just turned off dev settings and want to
2142                 // turn it on again
2143                 getActivity().getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE).edit()
2144                     .putBoolean(PREF_SHOW, true)
2145                     .apply();
2146             }
2147         } else if (dialog == mRootDialog) {
2148             if (which == DialogInterface.BUTTON_POSITIVE) {
2149                 writeRootAccessOptions(mSelectedRootValue);
2150             } else {
2151                 // Reset the option
2152                 writeRootAccessOptions("0");
2153             }
2154         } else if (dialog == mUpdateRecoveryDialog) {
2155             if (which == DialogInterface.BUTTON_POSITIVE) {
2156                 writeUpdateRecoveryOptions();
2157             }
2158         }
2159     }
2160
2161     public void onDismiss(DialogInterface dialog) {
2162         // Assuming that onClick gets called first
2163         if (dialog == mAdbDialog) {
2164             if (!mDialogClicked) {
2165                 mEnableAdb.setChecked(false);
2166             }
2167             mAdbDialog = null;
2168         } else if (dialog == mAdbTcpDialog) {
2169             updateAdbOverNetwork();
2170             mAdbTcpDialog = null;
2171         } else if (dialog == mEnableDialog) {
2172             if (!mDialogClicked) {
2173                 mSwitchBar.setChecked(false);
2174             }
2175             mEnableDialog = null;
2176         } else if (dialog == mRootDialog) {
2177             updateRootAccessOptions();
2178             mRootDialog = null;
2179         } else if (dialog == mUpdateRecoveryDialog) {
2180             updateUpdateRecoveryOptions();
2181             mUpdateRecoveryDialog = null;
2182         }
2183     }
2184
2185     @Override
2186     public void onDestroy() {
2187         dismissDialogs();
2188         super.onDestroy();
2189     }
2190
2191     void pokeSystemProperties() {
2192         if (!mDontPokeProperties) {
2193             //noinspection unchecked
2194             (new SystemPropPoker()).execute();
2195         }
2196     }
2197
2198     private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
2199         @Override
2200         public void onReceive(Context context, Intent intent) {
2201             updateUsbConfigurationValues();
2202         }
2203     };
2204
2205     static class SystemPropPoker extends AsyncTask<Void, Void, Void> {
2206         @Override
2207         protected Void doInBackground(Void... params) {
2208             String[] services;
2209             try {
2210                 services = ServiceManager.listServices();
2211             } catch (RemoteException e) {
2212                 return null;
2213             }
2214             for (String service : services) {
2215                 IBinder obj = ServiceManager.checkService(service);
2216                 if (obj != null) {
2217                     Parcel data = Parcel.obtain();
2218                     try {
2219                         obj.transact(IBinder.SYSPROPS_TRANSACTION, data, null, 0);
2220                     } catch (RemoteException e) {
2221                     } catch (Exception e) {
2222                         Log.i(TAG, "Someone wrote a bad service '" + service
2223                                 + "' that doesn't like to be poked: " + e);
2224                     }
2225                     data.recycle();
2226                 }
2227             }
2228             return null;
2229         }
2230     }
2231
2232     private static boolean isPackageInstalled(Context context, String packageName) {
2233         try {
2234             return context.getPackageManager().getPackageInfo(packageName, 0) != null;
2235         } catch (NameNotFoundException e) {
2236             return false;
2237         }
2238     }
2239
2240     /**
2241      * For Search.
2242      */
2243     public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
2244             new BaseSearchIndexProvider() {
2245
2246                 private boolean isShowingDeveloperOptions(Context context) {
2247                     return context.getSharedPreferences(DevelopmentSettings.PREF_FILE,
2248                             Context.MODE_PRIVATE).getBoolean(
2249                                     DevelopmentSettings.PREF_SHOW,
2250                                     android.os.Build.TYPE.equals("eng"));
2251                 }
2252
2253                 @Override
2254                 public List<SearchIndexableResource> getXmlResourcesToIndex(
2255                         Context context, boolean enabled) {
2256
2257                     if (!isShowingDeveloperOptions(context)) {
2258                         return null;
2259                     }
2260
2261                     final SearchIndexableResource sir = new SearchIndexableResource(context);
2262                     sir.xmlResId = R.xml.development_prefs;
2263                     return Arrays.asList(sir);
2264                 }
2265
2266                 @Override
2267                 public List<String> getNonIndexableKeys(Context context) {
2268                     if (!isShowingDeveloperOptions(context)) {
2269                         return null;
2270                     }
2271
2272                     final List<String> keys = new ArrayList<String>();
2273                     if (!showEnableOemUnlockPreference()) {
2274                         keys.add(ENABLE_OEM_UNLOCK);
2275                     }
2276                     if (!showEnableMultiWindowPreference()) {
2277                         keys.add(ENABLE_MULTI_WINDOW_KEY);
2278                     }
2279                     return keys;
2280                 }
2281             };
2282 }