OSDN Git Service

logd: settings: ro.config.low_ram support
[android-x86/packages-apps-Settings.git] / src / com / android / settings / DevelopmentSettings.java
1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.android.settings;
18
19 import android.app.Activity;
20 import android.app.ActivityManagerNative;
21 import android.app.AlertDialog;
22 import android.app.Dialog;
23 import android.app.admin.DevicePolicyManager;
24 import android.app.backup.IBackupManager;
25 import android.bluetooth.BluetoothAdapter;
26 import android.content.ContentResolver;
27 import android.content.Context;
28 import android.content.DialogInterface;
29 import android.content.Intent;
30 import android.content.pm.ApplicationInfo;
31 import android.content.pm.PackageManager;
32 import android.content.pm.PackageManager.NameNotFoundException;
33 import android.content.pm.ResolveInfo;
34 import android.database.Cursor;
35 import android.hardware.usb.IUsbManager;
36 import android.net.Uri;
37 import android.net.wifi.WifiManager;
38 import android.os.AsyncTask;
39 import android.os.BatteryManager;
40 import android.os.Build;
41 import android.os.Bundle;
42 import android.os.IBinder;
43 import android.os.Parcel;
44 import android.os.RemoteException;
45 import android.os.ServiceManager;
46 import android.os.StrictMode;
47 import android.os.SystemProperties;
48 import android.os.UserHandle;
49 import android.os.UserManager;
50 import android.preference.CheckBoxPreference;
51 import android.preference.ListPreference;
52 import android.preference.Preference;
53 import android.preference.Preference.OnPreferenceChangeListener;
54 import android.preference.PreferenceGroup;
55 import android.preference.PreferenceScreen;
56 import android.provider.SearchIndexableResource;
57 import android.provider.Settings;
58 import android.text.TextUtils;
59 import android.util.Log;
60 import android.view.HardwareRenderer;
61 import android.view.IWindowManager;
62 import android.view.View;
63 import android.view.accessibility.AccessibilityManager;
64 import android.webkit.WebView;
65 import android.widget.Switch;
66 import android.widget.TextView;
67
68 import com.android.settings.search.BaseSearchIndexProvider;
69 import com.android.settings.search.Indexable;
70 import com.android.settings.widget.SwitchBar;
71 import dalvik.system.VMRuntime;
72
73 import java.util.ArrayList;
74 import java.util.Arrays;
75 import java.util.HashSet;
76 import java.util.List;
77
78 /*
79  * Displays preferences for application developers.
80  */
81 public class DevelopmentSettings extends SettingsPreferenceFragment
82         implements DialogInterface.OnClickListener, DialogInterface.OnDismissListener,
83                 OnPreferenceChangeListener, SwitchBar.OnSwitchChangeListener, Indexable {
84     private static final String TAG = "DevelopmentSettings";
85
86     /**
87      * Preference file were development settings prefs are stored.
88      */
89     public static final String PREF_FILE = "development";
90
91     /**
92      * Whether to show the development settings to the user.  Default is false.
93      */
94     public static final String PREF_SHOW = "show";
95
96     private static final String ENABLE_ADB = "enable_adb";
97     private static final String CLEAR_ADB_KEYS = "clear_adb_keys";
98     private static final String ENABLE_TERMINAL = "enable_terminal";
99     private static final String KEEP_SCREEN_ON = "keep_screen_on";
100     private static final String BT_HCI_SNOOP_LOG = "bt_hci_snoop_log";
101     private static final String ENABLE_OEM_UNLOCK = "oem_unlock_enable";
102     private static final String ALLOW_MOCK_LOCATION = "allow_mock_location";
103     private static final String HDCP_CHECKING_KEY = "hdcp_checking";
104     private static final String HDCP_CHECKING_PROPERTY = "persist.sys.hdcp_checking";
105     private static final String LOCAL_BACKUP_PASSWORD = "local_backup_password";
106     private static final String HARDWARE_UI_PROPERTY = "persist.sys.ui.hw";
107     private static final String MSAA_PROPERTY = "debug.egl.force_msaa";
108     private static final String BUGREPORT = "bugreport";
109     private static final String BUGREPORT_IN_POWER_KEY = "bugreport_in_power";
110     private static final String OPENGL_TRACES_PROPERTY = "debug.egl.trace";
111
112     private static final String DEBUG_APP_KEY = "debug_app";
113     private static final String WAIT_FOR_DEBUGGER_KEY = "wait_for_debugger";
114     private static final String VERIFY_APPS_OVER_USB_KEY = "verify_apps_over_usb";
115     private static final String DEBUG_VIEW_ATTRIBUTES =  "debug_view_attributes";
116     private static final String STRICT_MODE_KEY = "strict_mode";
117     private static final String POINTER_LOCATION_KEY = "pointer_location";
118     private static final String SHOW_TOUCHES_KEY = "show_touches";
119     private static final String SHOW_SCREEN_UPDATES_KEY = "show_screen_updates";
120     private static final String DISABLE_OVERLAYS_KEY = "disable_overlays";
121     private static final String SIMULATE_COLOR_SPACE = "simulate_color_space";
122     private static final String USE_NUPLAYER_KEY = "use_nuplayer";
123     private static final String USB_AUDIO_KEY = "usb_audio";
124     private static final String USE_AWESOMEPLAYER_PROPERTY = "persist.sys.media.use-awesome";
125     private static final String SHOW_CPU_USAGE_KEY = "show_cpu_usage";
126     private static final String FORCE_HARDWARE_UI_KEY = "force_hw_ui";
127     private static final String FORCE_MSAA_KEY = "force_msaa";
128     private static final String TRACK_FRAME_TIME_KEY = "track_frame_time";
129     private static final String SHOW_NON_RECTANGULAR_CLIP_KEY = "show_non_rect_clip";
130     private static final String SHOW_HW_SCREEN_UPDATES_KEY = "show_hw_screen_udpates";
131     private static final String SHOW_HW_LAYERS_UPDATES_KEY = "show_hw_layers_udpates";
132     private static final String DEBUG_HW_OVERDRAW_KEY = "debug_hw_overdraw";
133     private static final String DEBUG_LAYOUT_KEY = "debug_layout";
134     private static final String FORCE_RTL_LAYOUT_KEY = "force_rtl_layout_all_locales";
135     private static final String WINDOW_ANIMATION_SCALE_KEY = "window_animation_scale";
136     private static final String TRANSITION_ANIMATION_SCALE_KEY = "transition_animation_scale";
137     private static final String ANIMATOR_DURATION_SCALE_KEY = "animator_duration_scale";
138     private static final String OVERLAY_DISPLAY_DEVICES_KEY = "overlay_display_devices";
139     private static final String DEBUG_DEBUGGING_CATEGORY_KEY = "debug_debugging_category";
140     private static final String DEBUG_APPLICATIONS_CATEGORY_KEY = "debug_applications_category";
141     private static final String WIFI_DISPLAY_CERTIFICATION_KEY = "wifi_display_certification";
142     private static final String WIFI_VERBOSE_LOGGING_KEY = "wifi_verbose_logging";
143     private static final String WIFI_AGGRESSIVE_HANDOVER_KEY = "wifi_aggressive_handover";
144     private static final String WIFI_ALLOW_SCAN_WITH_TRAFFIC_KEY = "wifi_allow_scan_with_traffic";
145     private static final String SELECT_LOGD_SIZE_KEY = "select_logd_size";
146     private static final String SELECT_LOGD_SIZE_PROPERTY = "persist.logd.size";
147     private static final String SELECT_LOGD_DEFAULT_SIZE_PROPERTY = "ro.logd.size";
148
149     private static final String OPENGL_TRACES_KEY = "enable_opengl_traces";
150
151     private static final String IMMEDIATELY_DESTROY_ACTIVITIES_KEY
152             = "immediately_destroy_activities";
153     private static final String APP_PROCESS_LIMIT_KEY = "app_process_limit";
154
155     private static final String SHOW_ALL_ANRS_KEY = "show_all_anrs";
156
157     private static final String WEBVIEW_DATA_REDUCTION_PROXY_KEY = "webview_data_reduction_proxy";
158     // GoogleSetting name for the data reduction proxy setting.
159     // Setting type: int ( 0 = disallow, 1 = allow )
160     private static final String WEBVIEW_DATA_REDUCTION_PROXY = "use_webview_data_reduction_proxy";
161
162     private static final String PROCESS_STATS = "proc_stats";
163
164     private static final String TAG_CONFIRM_ENFORCE = "confirm_enforce";
165
166     private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
167
168     private static final String TERMINAL_APP_PACKAGE = "com.android.terminal";
169
170     private static final int RESULT_DEBUG_APP = 1000;
171
172     private static final String PERSISTENT_DATA_BLOCK_PROP = "ro.frp.pst";
173
174     // The setting Uri. Used when querying GoogleSettings.
175     private static final Uri GOOGLE_SETTINGS_CONTENT_URI = Uri.parse("content://com.google.settings/partner");
176     private static final String GOOGLE_SETTINGS_COMPONENT = "com.google.android.gms";
177     private static final String GOOGLE_SETTINGS_ACTIVITY = ".app.settings.GoogleSettingsActivity";
178
179     private static String DEFAULT_LOG_RING_BUFFER_SIZE_IN_BYTES = "262144"; // 256K
180
181     private IWindowManager mWindowManager;
182     private IBackupManager mBackupManager;
183     private DevicePolicyManager mDpm;
184     private UserManager mUm;
185     private WifiManager mWifiManager;
186
187     private SwitchBar mSwitchBar;
188     private boolean mLastEnabledState;
189     private boolean mHaveDebugSettings;
190     private boolean mDontPokeProperties;
191
192     private CheckBoxPreference mEnableAdb;
193     private Preference mClearAdbKeys;
194     private CheckBoxPreference mEnableTerminal;
195     private Preference mBugreport;
196     private CheckBoxPreference mBugreportInPower;
197     private CheckBoxPreference mKeepScreenOn;
198     private CheckBoxPreference mBtHciSnoopLog;
199     private CheckBoxPreference mEnableOemUnlock;
200     private CheckBoxPreference mAllowMockLocation;
201     private CheckBoxPreference mDebugViewAttributes;
202
203     private PreferenceScreen mPassword;
204     private String mDebugApp;
205     private Preference mDebugAppPref;
206     private CheckBoxPreference mWaitForDebugger;
207     private CheckBoxPreference mVerifyAppsOverUsb;
208     private CheckBoxPreference mWifiDisplayCertification;
209     private CheckBoxPreference mWifiVerboseLogging;
210     private CheckBoxPreference mWifiAggressiveHandover;
211
212     private CheckBoxPreference mWifiAllowScansWithTraffic;
213     private CheckBoxPreference mStrictMode;
214     private CheckBoxPreference mPointerLocation;
215     private CheckBoxPreference mShowTouches;
216     private CheckBoxPreference mShowScreenUpdates;
217     private CheckBoxPreference mDisableOverlays;
218     private CheckBoxPreference mShowCpuUsage;
219     private CheckBoxPreference mForceHardwareUi;
220     private CheckBoxPreference mForceMsaa;
221     private CheckBoxPreference mShowHwScreenUpdates;
222     private CheckBoxPreference mShowHwLayersUpdates;
223     private CheckBoxPreference mDebugLayout;
224     private CheckBoxPreference mForceRtlLayout;
225     private ListPreference mDebugHwOverdraw;
226     private ListPreference mLogdSize;
227     private ListPreference mTrackFrameTime;
228     private ListPreference mShowNonRectClip;
229     private ListPreference mWindowAnimationScale;
230     private ListPreference mTransitionAnimationScale;
231     private ListPreference mAnimatorDurationScale;
232     private ListPreference mOverlayDisplayDevices;
233     private ListPreference mOpenGLTraces;
234
235     private ListPreference mSimulateColorSpace;
236
237     private CheckBoxPreference mUseNuplayer;
238     private CheckBoxPreference mUSBAudio;
239     private CheckBoxPreference mImmediatelyDestroyActivities;
240
241     private ListPreference mAppProcessLimit;
242
243     private CheckBoxPreference mShowAllANRs;
244
245     private CheckBoxPreference mWebViewDataReductionProxy;
246
247     private PreferenceScreen mProcessStats;
248     private final ArrayList<Preference> mAllPrefs = new ArrayList<Preference>();
249
250     private final ArrayList<CheckBoxPreference> mResetCbPrefs
251             = new ArrayList<CheckBoxPreference>();
252
253     private final HashSet<Preference> mDisabledPrefs = new HashSet<Preference>();
254     // To track whether a confirmation dialog was clicked.
255     private boolean mDialogClicked;
256     private Dialog mEnableDialog;
257     private Dialog mAdbDialog;
258
259     private Dialog mAdbKeysDialog;
260     private boolean mUnavailable;
261
262     @Override
263     public void onCreate(Bundle icicle) {
264         super.onCreate(icicle);
265
266         mWindowManager = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
267         mBackupManager = IBackupManager.Stub.asInterface(
268                 ServiceManager.getService(Context.BACKUP_SERVICE));
269         mDpm = (DevicePolicyManager)getActivity().getSystemService(Context.DEVICE_POLICY_SERVICE);
270         mUm = (UserManager) getSystemService(Context.USER_SERVICE);
271
272         mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
273
274         if (android.os.Process.myUserHandle().getIdentifier() != UserHandle.USER_OWNER
275                 || mUm.hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES)) {
276             mUnavailable = true;
277             setPreferenceScreen(new PreferenceScreen(getActivity(), null));
278             return;
279         }
280
281         addPreferencesFromResource(R.xml.development_prefs);
282
283         final PreferenceGroup debugDebuggingCategory = (PreferenceGroup)
284                 findPreference(DEBUG_DEBUGGING_CATEGORY_KEY);
285
286         mEnableAdb = findAndInitCheckboxPref(ENABLE_ADB);
287         mClearAdbKeys = findPreference(CLEAR_ADB_KEYS);
288         if (!SystemProperties.getBoolean("ro.adb.secure", false)) {
289             if (debugDebuggingCategory != null) {
290                 debugDebuggingCategory.removePreference(mClearAdbKeys);
291             }
292         }
293         mAllPrefs.add(mClearAdbKeys);
294         mEnableTerminal = findAndInitCheckboxPref(ENABLE_TERMINAL);
295         if (!isPackageInstalled(getActivity(), TERMINAL_APP_PACKAGE)) {
296             debugDebuggingCategory.removePreference(mEnableTerminal);
297             mEnableTerminal = null;
298         }
299
300         mBugreport = findPreference(BUGREPORT);
301         mBugreportInPower = findAndInitCheckboxPref(BUGREPORT_IN_POWER_KEY);
302         mKeepScreenOn = findAndInitCheckboxPref(KEEP_SCREEN_ON);
303         mBtHciSnoopLog = findAndInitCheckboxPref(BT_HCI_SNOOP_LOG);
304         mEnableOemUnlock = findAndInitCheckboxPref(ENABLE_OEM_UNLOCK);
305         if (!showEnableOemUnlockPreference()) {
306             removePreference(mEnableOemUnlock);
307             mEnableOemUnlock = null;
308         }
309         mAllowMockLocation = findAndInitCheckboxPref(ALLOW_MOCK_LOCATION);
310         mDebugViewAttributes = findAndInitCheckboxPref(DEBUG_VIEW_ATTRIBUTES);
311         mPassword = (PreferenceScreen) findPreference(LOCAL_BACKUP_PASSWORD);
312         mAllPrefs.add(mPassword);
313
314
315         if (!android.os.Process.myUserHandle().equals(UserHandle.OWNER)) {
316             disableForUser(mEnableAdb);
317             disableForUser(mClearAdbKeys);
318             disableForUser(mEnableTerminal);
319             disableForUser(mPassword);
320         }
321
322         mDebugAppPref = findPreference(DEBUG_APP_KEY);
323         mAllPrefs.add(mDebugAppPref);
324         mWaitForDebugger = findAndInitCheckboxPref(WAIT_FOR_DEBUGGER_KEY);
325         mVerifyAppsOverUsb = findAndInitCheckboxPref(VERIFY_APPS_OVER_USB_KEY);
326         if (!showVerifierSetting()) {
327             if (debugDebuggingCategory != null) {
328                 debugDebuggingCategory.removePreference(mVerifyAppsOverUsb);
329             } else {
330                 mVerifyAppsOverUsb.setEnabled(false);
331             }
332         }
333         mStrictMode = findAndInitCheckboxPref(STRICT_MODE_KEY);
334         mPointerLocation = findAndInitCheckboxPref(POINTER_LOCATION_KEY);
335         mShowTouches = findAndInitCheckboxPref(SHOW_TOUCHES_KEY);
336         mShowScreenUpdates = findAndInitCheckboxPref(SHOW_SCREEN_UPDATES_KEY);
337         mDisableOverlays = findAndInitCheckboxPref(DISABLE_OVERLAYS_KEY);
338         mShowCpuUsage = findAndInitCheckboxPref(SHOW_CPU_USAGE_KEY);
339         mForceHardwareUi = findAndInitCheckboxPref(FORCE_HARDWARE_UI_KEY);
340         mForceMsaa = findAndInitCheckboxPref(FORCE_MSAA_KEY);
341         mTrackFrameTime = addListPreference(TRACK_FRAME_TIME_KEY);
342         mShowNonRectClip = addListPreference(SHOW_NON_RECTANGULAR_CLIP_KEY);
343         mShowHwScreenUpdates = findAndInitCheckboxPref(SHOW_HW_SCREEN_UPDATES_KEY);
344         mShowHwLayersUpdates = findAndInitCheckboxPref(SHOW_HW_LAYERS_UPDATES_KEY);
345         mDebugLayout = findAndInitCheckboxPref(DEBUG_LAYOUT_KEY);
346         mForceRtlLayout = findAndInitCheckboxPref(FORCE_RTL_LAYOUT_KEY);
347         mDebugHwOverdraw = addListPreference(DEBUG_HW_OVERDRAW_KEY);
348         mWifiDisplayCertification = findAndInitCheckboxPref(WIFI_DISPLAY_CERTIFICATION_KEY);
349         mWifiVerboseLogging = findAndInitCheckboxPref(WIFI_VERBOSE_LOGGING_KEY);
350         mWifiAggressiveHandover = findAndInitCheckboxPref(WIFI_AGGRESSIVE_HANDOVER_KEY);
351         mWifiAllowScansWithTraffic = findAndInitCheckboxPref(WIFI_ALLOW_SCAN_WITH_TRAFFIC_KEY);
352         mLogdSize = addListPreference(SELECT_LOGD_SIZE_KEY);
353
354         mWindowAnimationScale = addListPreference(WINDOW_ANIMATION_SCALE_KEY);
355         mTransitionAnimationScale = addListPreference(TRANSITION_ANIMATION_SCALE_KEY);
356         mAnimatorDurationScale = addListPreference(ANIMATOR_DURATION_SCALE_KEY);
357         mOverlayDisplayDevices = addListPreference(OVERLAY_DISPLAY_DEVICES_KEY);
358         mOpenGLTraces = addListPreference(OPENGL_TRACES_KEY);
359         mSimulateColorSpace = addListPreference(SIMULATE_COLOR_SPACE);
360         mUseNuplayer = findAndInitCheckboxPref(USE_NUPLAYER_KEY);
361         mUSBAudio = findAndInitCheckboxPref(USB_AUDIO_KEY);
362
363         mImmediatelyDestroyActivities = (CheckBoxPreference) findPreference(
364                 IMMEDIATELY_DESTROY_ACTIVITIES_KEY);
365         mAllPrefs.add(mImmediatelyDestroyActivities);
366         mResetCbPrefs.add(mImmediatelyDestroyActivities);
367
368         mAppProcessLimit = addListPreference(APP_PROCESS_LIMIT_KEY);
369
370         mShowAllANRs = (CheckBoxPreference) findPreference(
371                 SHOW_ALL_ANRS_KEY);
372         mAllPrefs.add(mShowAllANRs);
373         mResetCbPrefs.add(mShowAllANRs);
374
375         Preference hdcpChecking = findPreference(HDCP_CHECKING_KEY);
376         if (hdcpChecking != null) {
377             mAllPrefs.add(hdcpChecking);
378             removePreferenceForProduction(hdcpChecking);
379         }
380
381         mProcessStats = (PreferenceScreen) findPreference(PROCESS_STATS);
382         mAllPrefs.add(mProcessStats);
383
384         mWebViewDataReductionProxy = findAndInitCheckboxPref(WEBVIEW_DATA_REDUCTION_PROXY_KEY);
385         mWebViewDataReductionProxy.setOnPreferenceChangeListener(
386                 new Preference.OnPreferenceChangeListener() {
387                     @Override
388                     public boolean onPreferenceChange(Preference preference, Object newValue) {
389                         return handleDataReductionProxyPreferenceChange();
390                     }
391                 });
392     }
393
394     private ListPreference addListPreference(String prefKey) {
395         ListPreference pref = (ListPreference) findPreference(prefKey);
396         mAllPrefs.add(pref);
397         pref.setOnPreferenceChangeListener(this);
398         return pref;
399     }
400
401     private void disableForUser(Preference pref) {
402         if (pref != null) {
403             pref.setEnabled(false);
404             mDisabledPrefs.add(pref);
405         }
406     }
407
408     private CheckBoxPreference findAndInitCheckboxPref(String key) {
409         CheckBoxPreference pref = (CheckBoxPreference) findPreference(key);
410         if (pref == null) {
411             throw new IllegalArgumentException("Cannot find preference with key = " + key);
412         }
413         mAllPrefs.add(pref);
414         mResetCbPrefs.add(pref);
415         return pref;
416     }
417
418     @Override
419     public void onActivityCreated(Bundle savedInstanceState) {
420         super.onActivityCreated(savedInstanceState);
421
422         final SettingsActivity activity = (SettingsActivity) getActivity();
423
424         mSwitchBar = activity.getSwitchBar();
425        if (mUnavailable) {
426             mSwitchBar.setEnabled(false);
427             return;
428         }
429
430         mSwitchBar.addOnSwitchChangeListener(this);
431     }
432
433     private boolean removePreferenceForProduction(Preference preference) {
434         if ("user".equals(Build.TYPE)) {
435             removePreference(preference);
436             return true;
437         }
438         return false;
439     }
440
441     private void removePreference(Preference preference) {
442         getPreferenceScreen().removePreference(preference);
443         mAllPrefs.remove(preference);
444     }
445
446     private void setPrefsEnabledState(boolean enabled) {
447         for (int i = 0; i < mAllPrefs.size(); i++) {
448             Preference pref = mAllPrefs.get(i);
449             pref.setEnabled(enabled && !mDisabledPrefs.contains(pref));
450         }
451         updateAllOptions();
452     }
453
454     @Override
455     public void onResume() {
456         super.onResume();
457
458         if (mUnavailable) {
459             // Show error message
460             TextView emptyView = (TextView) getView().findViewById(android.R.id.empty);
461             getListView().setEmptyView(emptyView);
462             if (emptyView != null) {
463                 emptyView.setText(R.string.development_settings_not_available);
464             }
465             return;
466         }
467
468         if (mDpm.getMaximumTimeToLock(null) > 0) {
469             // A DeviceAdmin has specified a maximum time until the device
470             // will lock...  in this case we can't allow the user to turn
471             // on "stay awake when plugged in" because that would defeat the
472             // restriction.
473             mDisabledPrefs.add(mKeepScreenOn);
474         } else {
475             mDisabledPrefs.remove(mKeepScreenOn);
476         }
477
478         final ContentResolver cr = getActivity().getContentResolver();
479         mLastEnabledState = Settings.Global.getInt(cr,
480                 Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0;
481         mSwitchBar.setChecked(mLastEnabledState);
482         setPrefsEnabledState(mLastEnabledState);
483
484         if (mHaveDebugSettings && !mLastEnabledState) {
485             // Overall debugging is disabled, but there are some debug
486             // settings that are enabled.  This is an invalid state.  Switch
487             // to debug settings being enabled, so the user knows there is
488             // stuff enabled and can turn it all off if they want.
489             Settings.Global.putInt(getActivity().getContentResolver(),
490                     Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 1);
491             mLastEnabledState = true;
492             mSwitchBar.setChecked(mLastEnabledState);
493             setPrefsEnabledState(mLastEnabledState);
494         }
495         mSwitchBar.show();
496     }
497
498     @Override
499     public void onDestroyView() {
500         super.onDestroyView();
501
502         if (mUnavailable) {
503             return;
504         }
505         mSwitchBar.removeOnSwitchChangeListener(this);
506         mSwitchBar.hide();
507     }
508
509     void updateCheckBox(CheckBoxPreference checkBox, boolean value) {
510         checkBox.setChecked(value);
511         mHaveDebugSettings |= value;
512     }
513
514     private void updateAllOptions() {
515         final Context context = getActivity();
516         final ContentResolver cr = context.getContentResolver();
517         mHaveDebugSettings = false;
518         updateCheckBox(mEnableAdb, Settings.Global.getInt(cr,
519                 Settings.Global.ADB_ENABLED, 0) != 0);
520         if (mEnableTerminal != null) {
521             updateCheckBox(mEnableTerminal,
522                     context.getPackageManager().getApplicationEnabledSetting(TERMINAL_APP_PACKAGE)
523                     == PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
524         }
525         updateCheckBox(mBugreportInPower, Settings.Secure.getInt(cr,
526                 Settings.Secure.BUGREPORT_IN_POWER_MENU, 0) != 0);
527         updateCheckBox(mKeepScreenOn, Settings.Global.getInt(cr,
528                 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0) != 0);
529         updateCheckBox(mBtHciSnoopLog, Settings.Secure.getInt(cr,
530                 Settings.Secure.BLUETOOTH_HCI_LOG, 0) != 0);
531         if (mEnableOemUnlock != null) {
532             updateCheckBox(mEnableOemUnlock, Utils.isOemUnlockEnabled(getActivity()));
533         }
534         updateCheckBox(mAllowMockLocation, Settings.Secure.getInt(cr,
535                 Settings.Secure.ALLOW_MOCK_LOCATION, 0) != 0);
536         updateCheckBox(mDebugViewAttributes, Settings.Global.getInt(cr,
537                 Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0);
538         updateHdcpValues();
539         updatePasswordSummary();
540         updateDebuggerOptions();
541         updateStrictModeVisualOptions();
542         updatePointerLocationOptions();
543         updateShowTouchesOptions();
544         updateFlingerOptions();
545         updateCpuUsageOptions();
546         updateHardwareUiOptions();
547         updateMsaaOptions();
548         updateTrackFrameTimeOptions();
549         updateShowNonRectClipOptions();
550         updateShowHwScreenUpdatesOptions();
551         updateShowHwLayersUpdatesOptions();
552         updateDebugHwOverdrawOptions();
553         updateDebugLayoutOptions();
554         updateAnimationScaleOptions();
555         updateOverlayDisplayDevicesOptions();
556         updateOpenGLTracesOptions();
557         updateImmediatelyDestroyActivitiesOptions();
558         updateAppProcessLimitOptions();
559         updateShowAllANRsOptions();
560         updateWebViewDataReductionProxyOptions();
561         updateVerifyAppsOverUsbOptions();
562         updateBugreportOptions();
563         updateForceRtlOptions();
564         updateLogdSizeValues();
565         updateWifiDisplayCertificationOptions();
566         updateWifiVerboseLoggingOptions();
567         updateWifiAggressiveHandoverOptions();
568         updateWifiAllowScansWithTrafficOptions();
569         updateSimulateColorSpace();
570         updateUseNuplayerOptions();
571         updateUSBAudioOptions();
572     }
573
574     private void resetDangerousOptions() {
575         mDontPokeProperties = true;
576         for (int i=0; i<mResetCbPrefs.size(); i++) {
577             CheckBoxPreference cb = mResetCbPrefs.get(i);
578             if (cb.isChecked()) {
579                 cb.setChecked(false);
580                 onPreferenceTreeClick(null, cb);
581             }
582         }
583         resetDebuggerOptions();
584         writeLogdSizeOption(null);
585         writeAnimationScaleOption(0, mWindowAnimationScale, null);
586         writeAnimationScaleOption(1, mTransitionAnimationScale, null);
587         writeAnimationScaleOption(2, mAnimatorDurationScale, null);
588         // Only poke the color space setting if we control it.
589         if (usingDevelopmentColorSpace()) {
590             writeSimulateColorSpace(-1);
591         }
592         writeOverlayDisplayDevicesOptions(null);
593         writeAppProcessLimitOptions(null);
594         mHaveDebugSettings = false;
595         updateAllOptions();
596         mDontPokeProperties = false;
597         pokeSystemProperties();
598     }
599
600     private void updateHdcpValues() {
601         ListPreference hdcpChecking = (ListPreference) findPreference(HDCP_CHECKING_KEY);
602         if (hdcpChecking != null) {
603             String currentValue = SystemProperties.get(HDCP_CHECKING_PROPERTY);
604             String[] values = getResources().getStringArray(R.array.hdcp_checking_values);
605             String[] summaries = getResources().getStringArray(R.array.hdcp_checking_summaries);
606             int index = 1; // Defaults to drm-only. Needs to match with R.array.hdcp_checking_values
607             for (int i = 0; i < values.length; i++) {
608                 if (currentValue.equals(values[i])) {
609                     index = i;
610                     break;
611                 }
612             }
613             hdcpChecking.setValue(values[index]);
614             hdcpChecking.setSummary(summaries[index]);
615             hdcpChecking.setOnPreferenceChangeListener(this);
616         }
617     }
618
619     private void updatePasswordSummary() {
620         try {
621             if (mBackupManager.hasBackupPassword()) {
622                 mPassword.setSummary(R.string.local_backup_password_summary_change);
623             } else {
624                 mPassword.setSummary(R.string.local_backup_password_summary_none);
625             }
626         } catch (RemoteException e) {
627             // Not much we can do here
628         }
629     }
630
631     private void writeBtHciSnoopLogOptions() {
632         BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
633         adapter.configHciSnoopLog(mBtHciSnoopLog.isChecked());
634         Settings.Secure.putInt(getActivity().getContentResolver(),
635                 Settings.Secure.BLUETOOTH_HCI_LOG,
636                 mBtHciSnoopLog.isChecked() ? 1 : 0);
637     }
638
639     private void writeDebuggerOptions() {
640         try {
641             ActivityManagerNative.getDefault().setDebugApp(
642                 mDebugApp, mWaitForDebugger.isChecked(), true);
643         } catch (RemoteException ex) {
644         }
645     }
646
647     private static void resetDebuggerOptions() {
648         try {
649             ActivityManagerNative.getDefault().setDebugApp(
650                     null, false, true);
651         } catch (RemoteException ex) {
652         }
653     }
654
655     private void updateDebuggerOptions() {
656         mDebugApp = Settings.Global.getString(
657                 getActivity().getContentResolver(), Settings.Global.DEBUG_APP);
658         updateCheckBox(mWaitForDebugger, Settings.Global.getInt(
659                 getActivity().getContentResolver(), Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0);
660         if (mDebugApp != null && mDebugApp.length() > 0) {
661             String label;
662             try {
663                 ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(mDebugApp,
664                         PackageManager.GET_DISABLED_COMPONENTS);
665                 CharSequence lab = getActivity().getPackageManager().getApplicationLabel(ai);
666                 label = lab != null ? lab.toString() : mDebugApp;
667             } catch (PackageManager.NameNotFoundException e) {
668                 label = mDebugApp;
669             }
670             mDebugAppPref.setSummary(getResources().getString(R.string.debug_app_set, label));
671             mWaitForDebugger.setEnabled(true);
672             mHaveDebugSettings = true;
673         } else {
674             mDebugAppPref.setSummary(getResources().getString(R.string.debug_app_not_set));
675             mWaitForDebugger.setEnabled(false);
676         }
677     }
678
679     private void updateVerifyAppsOverUsbOptions() {
680         updateCheckBox(mVerifyAppsOverUsb, Settings.Global.getInt(getActivity().getContentResolver(),
681                 Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) != 0);
682         mVerifyAppsOverUsb.setEnabled(enableVerifierSetting());
683     }
684
685     private void writeVerifyAppsOverUsbOptions() {
686         Settings.Global.putInt(getActivity().getContentResolver(),
687               Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, mVerifyAppsOverUsb.isChecked() ? 1 : 0);
688     }
689
690     private boolean enableVerifierSetting() {
691         final ContentResolver cr = getActivity().getContentResolver();
692         if (Settings.Global.getInt(cr, Settings.Global.ADB_ENABLED, 0) == 0) {
693             return false;
694         }
695         if (Settings.Global.getInt(cr, Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 0) {
696             return false;
697         } else {
698             final PackageManager pm = getActivity().getPackageManager();
699             final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
700             verification.setType(PACKAGE_MIME_TYPE);
701             verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
702             final List<ResolveInfo> receivers = pm.queryBroadcastReceivers(verification, 0);
703             if (receivers.size() == 0) {
704                 return false;
705             }
706         }
707         return true;
708     }
709
710     private boolean showVerifierSetting() {
711         return Settings.Global.getInt(getActivity().getContentResolver(),
712                 Settings.Global.PACKAGE_VERIFIER_SETTING_VISIBLE, 1) > 0;
713     }
714
715     private static boolean showEnableOemUnlockPreference() {
716         return !SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals("");
717     }
718
719     private void updateBugreportOptions() {
720         if ("user".equals(Build.TYPE)) {
721             final ContentResolver resolver = getActivity().getContentResolver();
722             final boolean adbEnabled = Settings.Global.getInt(
723                     resolver, Settings.Global.ADB_ENABLED, 0) != 0;
724             if (adbEnabled) {
725                 mBugreport.setEnabled(true);
726                 mBugreportInPower.setEnabled(true);
727             } else {
728                 mBugreport.setEnabled(false);
729                 mBugreportInPower.setEnabled(false);
730                 mBugreportInPower.setChecked(false);
731                 Settings.Secure.putInt(resolver, Settings.Secure.BUGREPORT_IN_POWER_MENU, 0);
732             }
733         } else {
734             mBugreportInPower.setEnabled(true);
735         }
736     }
737
738     // Returns the current state of the system property that controls
739     // strictmode flashes.  One of:
740     //    0: not explicitly set one way or another
741     //    1: on
742     //    2: off
743     private static int currentStrictModeActiveIndex() {
744         if (TextUtils.isEmpty(SystemProperties.get(StrictMode.VISUAL_PROPERTY))) {
745             return 0;
746         }
747         boolean enabled = SystemProperties.getBoolean(StrictMode.VISUAL_PROPERTY, false);
748         return enabled ? 1 : 2;
749     }
750
751     private void writeStrictModeVisualOptions() {
752         try {
753             mWindowManager.setStrictModeVisualIndicatorPreference(mStrictMode.isChecked()
754                     ? "1" : "");
755         } catch (RemoteException e) {
756         }
757     }
758
759     private void updateStrictModeVisualOptions() {
760         updateCheckBox(mStrictMode, currentStrictModeActiveIndex() == 1);
761     }
762
763     private void writePointerLocationOptions() {
764         Settings.System.putInt(getActivity().getContentResolver(),
765                 Settings.System.POINTER_LOCATION, mPointerLocation.isChecked() ? 1 : 0);
766     }
767
768     private void updatePointerLocationOptions() {
769         updateCheckBox(mPointerLocation, Settings.System.getInt(getActivity().getContentResolver(),
770                 Settings.System.POINTER_LOCATION, 0) != 0);
771     }
772
773     private void writeShowTouchesOptions() {
774         Settings.System.putInt(getActivity().getContentResolver(),
775                 Settings.System.SHOW_TOUCHES, mShowTouches.isChecked() ? 1 : 0);
776     }
777
778     private void updateShowTouchesOptions() {
779         updateCheckBox(mShowTouches, Settings.System.getInt(getActivity().getContentResolver(),
780                 Settings.System.SHOW_TOUCHES, 0) != 0);
781     }
782
783     private void updateFlingerOptions() {
784         // magic communication with surface flinger.
785         try {
786             IBinder flinger = ServiceManager.getService("SurfaceFlinger");
787             if (flinger != null) {
788                 Parcel data = Parcel.obtain();
789                 Parcel reply = Parcel.obtain();
790                 data.writeInterfaceToken("android.ui.ISurfaceComposer");
791                 flinger.transact(1010, data, reply, 0);
792                 @SuppressWarnings("unused")
793                 int showCpu = reply.readInt();
794                 @SuppressWarnings("unused")
795                 int enableGL = reply.readInt();
796                 int showUpdates = reply.readInt();
797                 updateCheckBox(mShowScreenUpdates, showUpdates != 0);
798                 @SuppressWarnings("unused")
799                 int showBackground = reply.readInt();
800                 int disableOverlays = reply.readInt();
801                 updateCheckBox(mDisableOverlays, disableOverlays != 0);
802                 reply.recycle();
803                 data.recycle();
804             }
805         } catch (RemoteException ex) {
806         }
807     }
808
809     private void writeShowUpdatesOption() {
810         try {
811             IBinder flinger = ServiceManager.getService("SurfaceFlinger");
812             if (flinger != null) {
813                 Parcel data = Parcel.obtain();
814                 data.writeInterfaceToken("android.ui.ISurfaceComposer");
815                 final int showUpdates = mShowScreenUpdates.isChecked() ? 1 : 0;
816                 data.writeInt(showUpdates);
817                 flinger.transact(1002, data, null, 0);
818                 data.recycle();
819
820                 updateFlingerOptions();
821             }
822         } catch (RemoteException ex) {
823         }
824     }
825
826     private void writeDisableOverlaysOption() {
827         try {
828             IBinder flinger = ServiceManager.getService("SurfaceFlinger");
829             if (flinger != null) {
830                 Parcel data = Parcel.obtain();
831                 data.writeInterfaceToken("android.ui.ISurfaceComposer");
832                 final int disableOverlays = mDisableOverlays.isChecked() ? 1 : 0;
833                 data.writeInt(disableOverlays);
834                 flinger.transact(1008, data, null, 0);
835                 data.recycle();
836
837                 updateFlingerOptions();
838             }
839         } catch (RemoteException ex) {
840         }
841     }
842
843     private void updateHardwareUiOptions() {
844         updateCheckBox(mForceHardwareUi, SystemProperties.getBoolean(HARDWARE_UI_PROPERTY, false));
845     }
846
847     private void writeHardwareUiOptions() {
848         SystemProperties.set(HARDWARE_UI_PROPERTY, mForceHardwareUi.isChecked() ? "true" : "false");
849         pokeSystemProperties();
850     }
851
852     private void updateMsaaOptions() {
853         updateCheckBox(mForceMsaa, SystemProperties.getBoolean(MSAA_PROPERTY, false));
854     }
855
856     private void writeMsaaOptions() {
857         SystemProperties.set(MSAA_PROPERTY, mForceMsaa.isChecked() ? "true" : "false");
858         pokeSystemProperties();
859     }
860
861     private void updateTrackFrameTimeOptions() {
862         String value = SystemProperties.get(HardwareRenderer.PROFILE_PROPERTY);
863         if (value == null) {
864             value = "";
865         }
866
867         CharSequence[] values = mTrackFrameTime.getEntryValues();
868         for (int i = 0; i < values.length; i++) {
869             if (value.contentEquals(values[i])) {
870                 mTrackFrameTime.setValueIndex(i);
871                 mTrackFrameTime.setSummary(mTrackFrameTime.getEntries()[i]);
872                 return;
873             }
874         }
875         mTrackFrameTime.setValueIndex(0);
876         mTrackFrameTime.setSummary(mTrackFrameTime.getEntries()[0]);
877     }
878
879     private void writeTrackFrameTimeOptions(Object newValue) {
880         SystemProperties.set(HardwareRenderer.PROFILE_PROPERTY,
881                 newValue == null ? "" : newValue.toString());
882         pokeSystemProperties();
883         updateTrackFrameTimeOptions();
884     }
885
886     private void updateShowNonRectClipOptions() {
887         String value = SystemProperties.get(
888                 HardwareRenderer.DEBUG_SHOW_NON_RECTANGULAR_CLIP_PROPERTY);
889         if (value == null) {
890             value = "hide";
891         }
892
893         CharSequence[] values = mShowNonRectClip.getEntryValues();
894         for (int i = 0; i < values.length; i++) {
895             if (value.contentEquals(values[i])) {
896                 mShowNonRectClip.setValueIndex(i);
897                 mShowNonRectClip.setSummary(mShowNonRectClip.getEntries()[i]);
898                 return;
899             }
900         }
901         mShowNonRectClip.setValueIndex(0);
902         mShowNonRectClip.setSummary(mShowNonRectClip.getEntries()[0]);
903     }
904
905     private void writeShowNonRectClipOptions(Object newValue) {
906         SystemProperties.set(HardwareRenderer.DEBUG_SHOW_NON_RECTANGULAR_CLIP_PROPERTY,
907                 newValue == null ? "" : newValue.toString());
908         pokeSystemProperties();
909         updateShowNonRectClipOptions();
910     }
911
912     private void updateShowHwScreenUpdatesOptions() {
913         updateCheckBox(mShowHwScreenUpdates,
914                 SystemProperties.getBoolean(HardwareRenderer.DEBUG_DIRTY_REGIONS_PROPERTY, false));
915     }
916
917     private void writeShowHwScreenUpdatesOptions() {
918         SystemProperties.set(HardwareRenderer.DEBUG_DIRTY_REGIONS_PROPERTY,
919                 mShowHwScreenUpdates.isChecked() ? "true" : null);
920         pokeSystemProperties();
921     }
922
923     private void updateShowHwLayersUpdatesOptions() {
924         updateCheckBox(mShowHwLayersUpdates, SystemProperties.getBoolean(
925                 HardwareRenderer.DEBUG_SHOW_LAYERS_UPDATES_PROPERTY, false));
926     }
927
928     private void writeShowHwLayersUpdatesOptions() {
929         SystemProperties.set(HardwareRenderer.DEBUG_SHOW_LAYERS_UPDATES_PROPERTY,
930                 mShowHwLayersUpdates.isChecked() ? "true" : null);
931         pokeSystemProperties();
932     }
933
934     private void updateDebugHwOverdrawOptions() {
935         String value = SystemProperties.get(HardwareRenderer.DEBUG_OVERDRAW_PROPERTY);
936         if (value == null) {
937             value = "";
938         }
939
940         CharSequence[] values = mDebugHwOverdraw.getEntryValues();
941         for (int i = 0; i < values.length; i++) {
942             if (value.contentEquals(values[i])) {
943                 mDebugHwOverdraw.setValueIndex(i);
944                 mDebugHwOverdraw.setSummary(mDebugHwOverdraw.getEntries()[i]);
945                 return;
946             }
947         }
948         mDebugHwOverdraw.setValueIndex(0);
949         mDebugHwOverdraw.setSummary(mDebugHwOverdraw.getEntries()[0]);
950     }
951
952     private void writeDebugHwOverdrawOptions(Object newValue) {
953         SystemProperties.set(HardwareRenderer.DEBUG_OVERDRAW_PROPERTY,
954                 newValue == null ? "" : newValue.toString());
955         pokeSystemProperties();
956         updateDebugHwOverdrawOptions();
957     }
958
959     private void updateDebugLayoutOptions() {
960         updateCheckBox(mDebugLayout,
961                 SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false));
962     }
963
964     private void writeDebugLayoutOptions() {
965         SystemProperties.set(View.DEBUG_LAYOUT_PROPERTY,
966                 mDebugLayout.isChecked() ? "true" : "false");
967         pokeSystemProperties();
968     }
969
970     private void updateSimulateColorSpace() {
971         final ContentResolver cr = getContentResolver();
972         final boolean enabled = Settings.Secure.getInt(
973                 cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 0) != 0;
974         if (enabled) {
975             final String mode = Integer.toString(Settings.Secure.getInt(
976                     cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER,
977                     AccessibilityManager.DALTONIZER_DISABLED));
978             mSimulateColorSpace.setValue(mode);
979             final int index = mSimulateColorSpace.findIndexOfValue(mode);
980             if (index < 0) {
981                 // We're using a mode controlled by accessibility preferences.
982                 mSimulateColorSpace.setSummary(getString(R.string.daltonizer_type_overridden,
983                         getString(R.string.accessibility_display_daltonizer_preference_title)));
984             } else {
985                 mSimulateColorSpace.setSummary("%s");
986             }
987         } else {
988             mSimulateColorSpace.setValue(
989                     Integer.toString(AccessibilityManager.DALTONIZER_DISABLED));
990         }
991     }
992
993     /**
994      * @return <code>true</code> if the color space preference is currently
995      *         controlled by development settings
996      */
997     private boolean usingDevelopmentColorSpace() {
998         final ContentResolver cr = getContentResolver();
999         final boolean enabled = Settings.Secure.getInt(
1000                 cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 0) != 0;
1001         if (enabled) {
1002             final String mode = Integer.toString(Settings.Secure.getInt(
1003                     cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER,
1004                     AccessibilityManager.DALTONIZER_DISABLED));
1005             final int index = mSimulateColorSpace.findIndexOfValue(mode);
1006             if (index >= 0) {
1007                 // We're using a mode controlled by developer preferences.
1008                 return true;
1009             }
1010         }
1011         return false;
1012     }
1013
1014     private void writeSimulateColorSpace(Object value) {
1015         final ContentResolver cr = getContentResolver();
1016         final int newMode = Integer.parseInt(value.toString());
1017         if (newMode < 0) {
1018             Settings.Secure.putInt(cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 0);
1019         } else {
1020             Settings.Secure.putInt(cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER_ENABLED, 1);
1021             Settings.Secure.putInt(cr, Settings.Secure.ACCESSIBILITY_DISPLAY_DALTONIZER, newMode);
1022         }
1023     }
1024
1025     private void updateUseNuplayerOptions() {
1026         updateCheckBox(
1027                 mUseNuplayer, !SystemProperties.getBoolean(USE_AWESOMEPLAYER_PROPERTY, false));
1028     }
1029
1030     private void writeUseNuplayerOptions() {
1031         SystemProperties.set(
1032                 USE_AWESOMEPLAYER_PROPERTY, mUseNuplayer.isChecked() ? "false" : "true");
1033         pokeSystemProperties();
1034     }
1035
1036     private void updateUSBAudioOptions() {
1037         updateCheckBox(mUSBAudio, Settings.Secure.getInt(getContentResolver(),
1038                 Settings.Secure.USB_AUDIO_AUTOMATIC_ROUTING_DISABLED, 0) != 0);
1039     }
1040
1041     private void writeUSBAudioOptions() {
1042         Settings.Secure.putInt(getContentResolver(),
1043                 Settings.Secure.USB_AUDIO_AUTOMATIC_ROUTING_DISABLED,
1044                 mUSBAudio.isChecked() ? 1 : 0);
1045     }
1046
1047     private void updateForceRtlOptions() {
1048         updateCheckBox(mForceRtlLayout, Settings.Global.getInt(getActivity().getContentResolver(),
1049                 Settings.Global.DEVELOPMENT_FORCE_RTL, 0) != 0);
1050     }
1051
1052     private void writeForceRtlOptions() {
1053         boolean value = mForceRtlLayout.isChecked();
1054         Settings.Global.putInt(getActivity().getContentResolver(),
1055                 Settings.Global.DEVELOPMENT_FORCE_RTL, value ? 1 : 0);
1056         SystemProperties.set(Settings.Global.DEVELOPMENT_FORCE_RTL, value ? "1" : "0");
1057         LocalePicker.updateLocale(getActivity().getResources().getConfiguration().locale);
1058     }
1059
1060     private void updateWifiDisplayCertificationOptions() {
1061         updateCheckBox(mWifiDisplayCertification, Settings.Global.getInt(
1062                 getActivity().getContentResolver(),
1063                 Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON, 0) != 0);
1064     }
1065
1066     private void writeWifiDisplayCertificationOptions() {
1067         Settings.Global.putInt(getActivity().getContentResolver(),
1068                 Settings.Global.WIFI_DISPLAY_CERTIFICATION_ON,
1069                 mWifiDisplayCertification.isChecked() ? 1 : 0);
1070     }
1071
1072     private void updateWifiVerboseLoggingOptions() {
1073         boolean enabled = mWifiManager.getVerboseLoggingLevel() > 0;
1074         updateCheckBox(mWifiVerboseLogging, enabled);
1075     }
1076
1077     private void writeWifiVerboseLoggingOptions() {
1078         mWifiManager.enableVerboseLogging(mWifiVerboseLogging.isChecked() ? 1 : 0);
1079     }
1080
1081     private void updateWifiAggressiveHandoverOptions() {
1082         boolean enabled = mWifiManager.getAggressiveHandover() > 0;
1083         updateCheckBox(mWifiAggressiveHandover, enabled);
1084     }
1085
1086     private void writeWifiAggressiveHandoverOptions() {
1087         mWifiManager.enableAggressiveHandover(mWifiAggressiveHandover.isChecked() ? 1 : 0);
1088     }
1089
1090     private void updateWifiAllowScansWithTrafficOptions() {
1091         boolean enabled = mWifiManager.getAllowScansWithTraffic() > 0;
1092         updateCheckBox(mWifiAllowScansWithTraffic, enabled);
1093     }
1094
1095     private void writeWifiAllowScansWithTrafficOptions() {
1096         mWifiManager.setAllowScansWithTraffic(mWifiAllowScansWithTraffic.isChecked() ? 1 : 0);
1097     }
1098
1099     private void updateLogdSizeValues() {
1100         if (mLogdSize != null) {
1101             String currentValue = SystemProperties.get(SELECT_LOGD_SIZE_PROPERTY);
1102             if (currentValue == null) {
1103                 currentValue = SystemProperties.get(SELECT_LOGD_DEFAULT_SIZE_PROPERTY);
1104                 if (currentValue == null) {
1105                     currentValue = "256K";
1106                 }
1107             }
1108             String[] values = getResources().getStringArray(R.array.select_logd_size_values);
1109             String[] titles = getResources().getStringArray(R.array.select_logd_size_titles);
1110             if (SystemProperties.get("ro.config.low_ram").equals("true")) {
1111                 mLogdSize.setEntries(R.array.select_logd_size_lowram_titles);
1112                 titles = getResources().getStringArray(R.array.select_logd_size_lowram_titles);
1113             }
1114             String[] summaries = getResources().getStringArray(R.array.select_logd_size_summaries);
1115             int index = 1; // punt to second entry if not found
1116             for (int i = 0; i < titles.length; i++) {
1117                 if (currentValue.equals(values[i])
1118                         || currentValue.equals(titles[i])) {
1119                     index = i;
1120                     break;
1121                 }
1122             }
1123             mLogdSize.setValue(values[index]);
1124             mLogdSize.setSummary(summaries[index]);
1125             mLogdSize.setOnPreferenceChangeListener(this);
1126         }
1127     }
1128
1129     private void writeLogdSizeOption(Object newValue) {
1130         String currentValue = SystemProperties.get(SELECT_LOGD_DEFAULT_SIZE_PROPERTY);
1131         if (currentValue != null) {
1132             DEFAULT_LOG_RING_BUFFER_SIZE_IN_BYTES = currentValue;
1133         }
1134         final String size = (newValue != null) ?
1135                 newValue.toString() : DEFAULT_LOG_RING_BUFFER_SIZE_IN_BYTES;
1136         SystemProperties.set(SELECT_LOGD_SIZE_PROPERTY, size);
1137         pokeSystemProperties();
1138         try {
1139             Process p = Runtime.getRuntime().exec("logcat -b all -G " + size);
1140             p.waitFor();
1141             Log.i(TAG, "Logcat ring buffer sizes set to: " + size);
1142         } catch (Exception e) {
1143             Log.w(TAG, "Cannot set logcat ring buffer sizes", e);
1144         }
1145         updateLogdSizeValues();
1146     }
1147
1148     private void updateCpuUsageOptions() {
1149         updateCheckBox(mShowCpuUsage, Settings.Global.getInt(getActivity().getContentResolver(),
1150                 Settings.Global.SHOW_PROCESSES, 0) != 0);
1151     }
1152
1153     private void writeCpuUsageOptions() {
1154         boolean value = mShowCpuUsage.isChecked();
1155         Settings.Global.putInt(getActivity().getContentResolver(),
1156                 Settings.Global.SHOW_PROCESSES, value ? 1 : 0);
1157         Intent service = (new Intent())
1158                 .setClassName("com.android.systemui", "com.android.systemui.LoadAverageService");
1159         if (value) {
1160             getActivity().startService(service);
1161         } else {
1162             getActivity().stopService(service);
1163         }
1164     }
1165
1166     private void writeImmediatelyDestroyActivitiesOptions() {
1167         try {
1168             ActivityManagerNative.getDefault().setAlwaysFinish(
1169                     mImmediatelyDestroyActivities.isChecked());
1170         } catch (RemoteException ex) {
1171         }
1172     }
1173
1174     private void updateImmediatelyDestroyActivitiesOptions() {
1175         updateCheckBox(mImmediatelyDestroyActivities, Settings.Global.getInt(
1176             getActivity().getContentResolver(), Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0);
1177     }
1178
1179     private void updateAnimationScaleValue(int which, ListPreference pref) {
1180         try {
1181             float scale = mWindowManager.getAnimationScale(which);
1182             if (scale != 1) {
1183                 mHaveDebugSettings = true;
1184             }
1185             CharSequence[] values = pref.getEntryValues();
1186             for (int i=0; i<values.length; i++) {
1187                 float val = Float.parseFloat(values[i].toString());
1188                 if (scale <= val) {
1189                     pref.setValueIndex(i);
1190                     pref.setSummary(pref.getEntries()[i]);
1191                     return;
1192                 }
1193             }
1194             pref.setValueIndex(values.length-1);
1195             pref.setSummary(pref.getEntries()[0]);
1196         } catch (RemoteException e) {
1197         }
1198     }
1199
1200     private void updateAnimationScaleOptions() {
1201         updateAnimationScaleValue(0, mWindowAnimationScale);
1202         updateAnimationScaleValue(1, mTransitionAnimationScale);
1203         updateAnimationScaleValue(2, mAnimatorDurationScale);
1204     }
1205
1206     private void writeAnimationScaleOption(int which, ListPreference pref, Object newValue) {
1207         try {
1208             float scale = newValue != null ? Float.parseFloat(newValue.toString()) : 1;
1209             mWindowManager.setAnimationScale(which, scale);
1210             updateAnimationScaleValue(which, pref);
1211         } catch (RemoteException e) {
1212         }
1213     }
1214
1215     private void updateOverlayDisplayDevicesOptions() {
1216         String value = Settings.Global.getString(getActivity().getContentResolver(),
1217                 Settings.Global.OVERLAY_DISPLAY_DEVICES);
1218         if (value == null) {
1219             value = "";
1220         }
1221
1222         CharSequence[] values = mOverlayDisplayDevices.getEntryValues();
1223         for (int i = 0; i < values.length; i++) {
1224             if (value.contentEquals(values[i])) {
1225                 mOverlayDisplayDevices.setValueIndex(i);
1226                 mOverlayDisplayDevices.setSummary(mOverlayDisplayDevices.getEntries()[i]);
1227                 return;
1228             }
1229         }
1230         mOverlayDisplayDevices.setValueIndex(0);
1231         mOverlayDisplayDevices.setSummary(mOverlayDisplayDevices.getEntries()[0]);
1232     }
1233
1234     private void writeOverlayDisplayDevicesOptions(Object newValue) {
1235         Settings.Global.putString(getActivity().getContentResolver(),
1236                 Settings.Global.OVERLAY_DISPLAY_DEVICES, (String)newValue);
1237         updateOverlayDisplayDevicesOptions();
1238     }
1239
1240     private void updateOpenGLTracesOptions() {
1241         String value = SystemProperties.get(OPENGL_TRACES_PROPERTY);
1242         if (value == null) {
1243             value = "";
1244         }
1245
1246         CharSequence[] values = mOpenGLTraces.getEntryValues();
1247         for (int i = 0; i < values.length; i++) {
1248             if (value.contentEquals(values[i])) {
1249                 mOpenGLTraces.setValueIndex(i);
1250                 mOpenGLTraces.setSummary(mOpenGLTraces.getEntries()[i]);
1251                 return;
1252             }
1253         }
1254         mOpenGLTraces.setValueIndex(0);
1255         mOpenGLTraces.setSummary(mOpenGLTraces.getEntries()[0]);
1256     }
1257
1258     private void writeOpenGLTracesOptions(Object newValue) {
1259         SystemProperties.set(OPENGL_TRACES_PROPERTY, newValue == null ? "" : newValue.toString());
1260         pokeSystemProperties();
1261         updateOpenGLTracesOptions();
1262     }
1263
1264     private void updateAppProcessLimitOptions() {
1265         try {
1266             int limit = ActivityManagerNative.getDefault().getProcessLimit();
1267             CharSequence[] values = mAppProcessLimit.getEntryValues();
1268             for (int i=0; i<values.length; i++) {
1269                 int val = Integer.parseInt(values[i].toString());
1270                 if (val >= limit) {
1271                     if (i != 0) {
1272                         mHaveDebugSettings = true;
1273                     }
1274                     mAppProcessLimit.setValueIndex(i);
1275                     mAppProcessLimit.setSummary(mAppProcessLimit.getEntries()[i]);
1276                     return;
1277                 }
1278             }
1279             mAppProcessLimit.setValueIndex(0);
1280             mAppProcessLimit.setSummary(mAppProcessLimit.getEntries()[0]);
1281         } catch (RemoteException e) {
1282         }
1283     }
1284
1285     private void writeAppProcessLimitOptions(Object newValue) {
1286         try {
1287             int limit = newValue != null ? Integer.parseInt(newValue.toString()) : -1;
1288             ActivityManagerNative.getDefault().setProcessLimit(limit);
1289             updateAppProcessLimitOptions();
1290         } catch (RemoteException e) {
1291         }
1292     }
1293
1294     private void writeShowAllANRsOptions() {
1295         Settings.Secure.putInt(getActivity().getContentResolver(),
1296                 Settings.Secure.ANR_SHOW_BACKGROUND,
1297                 mShowAllANRs.isChecked() ? 1 : 0);
1298     }
1299
1300     private void updateShowAllANRsOptions() {
1301         updateCheckBox(mShowAllANRs, Settings.Secure.getInt(
1302             getActivity().getContentResolver(), Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0);
1303     }
1304
1305     // Reads the googlesetting and converts to an int. Throws an exception if GoogleSettings
1306     // provider does not exist or if the setting name cannot be found.
1307     private int getGoogleSettingValue(String name) throws Exception {
1308         String value = null;
1309         Cursor c = null;
1310         try {
1311             ContentResolver resolver = getActivity().getContentResolver();
1312             c = resolver.query(GOOGLE_SETTINGS_CONTENT_URI, new String[] { "value" },
1313                     "name=?", new String[]{ name }, null);
1314             if (c != null && c.moveToNext()) value = c.getString(0);
1315         } finally {
1316             if (c != null) c.close();
1317         }
1318         // Throw an exception if value is null. This will indicate that setting is not found.
1319         return Integer.parseInt(value);
1320     }
1321
1322     private boolean handleDataReductionProxyPreferenceChange() {
1323         int val;
1324         try {
1325             val = getGoogleSettingValue(WEBVIEW_DATA_REDUCTION_PROXY);
1326         } catch (Exception e) {
1327             // Accessing GoogleSettings failed. Use the developer setting.
1328             return true;
1329         }
1330
1331         Intent i = new Intent();
1332         i.setClassName(GOOGLE_SETTINGS_COMPONENT,
1333                 GOOGLE_SETTINGS_COMPONENT + GOOGLE_SETTINGS_ACTIVITY);
1334         try {
1335             startActivity(i);
1336         } catch (android.content.ActivityNotFoundException ex) {
1337             // We found the GoogleSetting but for some reason activity not found.
1338             // Do our best and put an alert dialog
1339             new AlertDialog.Builder(getActivity()).setMessage(
1340                     getActivity().getResources().getString(
1341                         R.string.dev_settings_use_google_settings))
1342                         .setPositiveButton(android.R.string.ok, this)
1343                         .show();
1344         }
1345         // Use GoogleSettings to set.
1346         return false;
1347     }
1348
1349     private void writeWebViewDataReductionProxyOptions() {
1350         Settings.Secure.putInt(getActivity().getContentResolver(),
1351                 Settings.Secure.WEBVIEW_DATA_REDUCTION_PROXY,
1352                 mWebViewDataReductionProxy.isChecked() ? 1 : 0);
1353         Intent intent = new Intent(WebView.DATA_REDUCTION_PROXY_SETTING_CHANGED);
1354         // Broadcast to all apps running as current user.
1355         getActivity().sendBroadcastAsUser(intent, UserHandle.CURRENT);
1356     }
1357
1358     private void updateWebViewDataReductionProxyOptions() {
1359         int val = -1;
1360         try {
1361               val = getGoogleSettingValue(WEBVIEW_DATA_REDUCTION_PROXY);
1362         } catch (Exception e) {
1363             // Accessing GoogleSettings failed. Use the developer setting
1364         }
1365         if (val == -1) {
1366             val = Settings.Secure.getInt(getActivity().getContentResolver(),
1367                     Settings.Secure.WEBVIEW_DATA_REDUCTION_PROXY, 0);
1368         }
1369         updateCheckBox(mWebViewDataReductionProxy, val != 0);
1370     }
1371
1372     @Override
1373     public void onSwitchChanged(Switch switchView, boolean isChecked) {
1374         if (switchView != mSwitchBar.getSwitch()) {
1375             return;
1376         }
1377         if (isChecked != mLastEnabledState) {
1378             if (isChecked) {
1379                 mDialogClicked = false;
1380                 if (mEnableDialog != null) dismissDialogs();
1381                 mEnableDialog = new AlertDialog.Builder(getActivity()).setMessage(
1382                         getActivity().getResources().getString(
1383                                 R.string.dev_settings_warning_message))
1384                         .setTitle(R.string.dev_settings_warning_title)
1385                         .setPositiveButton(android.R.string.yes, this)
1386                         .setNegativeButton(android.R.string.no, this)
1387                         .show();
1388                 mEnableDialog.setOnDismissListener(this);
1389             } else {
1390                 resetDangerousOptions();
1391                 Settings.Global.putInt(getActivity().getContentResolver(),
1392                         Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0);
1393                 mLastEnabledState = isChecked;
1394                 setPrefsEnabledState(mLastEnabledState);
1395             }
1396         }
1397     }
1398
1399     @Override
1400     public void onActivityResult(int requestCode, int resultCode, Intent data) {
1401         if (requestCode == RESULT_DEBUG_APP) {
1402             if (resultCode == Activity.RESULT_OK) {
1403                 mDebugApp = data.getAction();
1404                 writeDebuggerOptions();
1405                 updateDebuggerOptions();
1406             }
1407         } else {
1408             super.onActivityResult(requestCode, resultCode, data);
1409         }
1410     }
1411
1412     @Override
1413     public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
1414         if (Utils.isMonkeyRunning()) {
1415             return false;
1416         }
1417
1418         if (preference == mEnableAdb) {
1419             if (mEnableAdb.isChecked()) {
1420                 mDialogClicked = false;
1421                 if (mAdbDialog != null) dismissDialogs();
1422                 mAdbDialog = new AlertDialog.Builder(getActivity()).setMessage(
1423                         getActivity().getResources().getString(R.string.adb_warning_message))
1424                         .setTitle(R.string.adb_warning_title)
1425                         .setPositiveButton(android.R.string.yes, this)
1426                         .setNegativeButton(android.R.string.no, this)
1427                         .show();
1428                 mAdbDialog.setOnDismissListener(this);
1429             } else {
1430                 Settings.Global.putInt(getActivity().getContentResolver(),
1431                         Settings.Global.ADB_ENABLED, 0);
1432                 mVerifyAppsOverUsb.setEnabled(false);
1433                 mVerifyAppsOverUsb.setChecked(false);
1434                 updateBugreportOptions();
1435             }
1436         } else if (preference == mClearAdbKeys) {
1437             if (mAdbKeysDialog != null) dismissDialogs();
1438             mAdbKeysDialog = new AlertDialog.Builder(getActivity())
1439                         .setMessage(R.string.adb_keys_warning_message)
1440                         .setPositiveButton(android.R.string.ok, this)
1441                         .setNegativeButton(android.R.string.cancel, null)
1442                         .show();
1443         } else if (preference == mEnableTerminal) {
1444             final PackageManager pm = getActivity().getPackageManager();
1445             pm.setApplicationEnabledSetting(TERMINAL_APP_PACKAGE,
1446                     mEnableTerminal.isChecked() ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
1447                             : PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0);
1448         } else if (preference == mBugreportInPower) {
1449             Settings.Secure.putInt(getActivity().getContentResolver(),
1450                     Settings.Secure.BUGREPORT_IN_POWER_MENU,
1451                     mBugreportInPower.isChecked() ? 1 : 0);
1452         } else if (preference == mKeepScreenOn) {
1453             Settings.Global.putInt(getActivity().getContentResolver(),
1454                     Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
1455                     mKeepScreenOn.isChecked() ?
1456                             (BatteryManager.BATTERY_PLUGGED_AC | BatteryManager.BATTERY_PLUGGED_USB) : 0);
1457         } else if (preference == mBtHciSnoopLog) {
1458             writeBtHciSnoopLogOptions();
1459         } else if (preference == mEnableOemUnlock) {
1460             Utils.setOemUnlockEnabled(getActivity(), mEnableOemUnlock.isChecked());
1461         } else if (preference == mAllowMockLocation) {
1462             Settings.Secure.putInt(getActivity().getContentResolver(),
1463                     Settings.Secure.ALLOW_MOCK_LOCATION,
1464                     mAllowMockLocation.isChecked() ? 1 : 0);
1465         } else if (preference == mDebugViewAttributes) {
1466             Settings.Global.putInt(getActivity().getContentResolver(),
1467                     Settings.Global.DEBUG_VIEW_ATTRIBUTES,
1468                     mDebugViewAttributes.isChecked() ? 1 : 0);
1469         } else if (preference == mDebugAppPref) {
1470             startActivityForResult(new Intent(getActivity(), AppPicker.class), RESULT_DEBUG_APP);
1471         } else if (preference == mWaitForDebugger) {
1472             writeDebuggerOptions();
1473         } else if (preference == mVerifyAppsOverUsb) {
1474             writeVerifyAppsOverUsbOptions();
1475         } else if (preference == mStrictMode) {
1476             writeStrictModeVisualOptions();
1477         } else if (preference == mPointerLocation) {
1478             writePointerLocationOptions();
1479         } else if (preference == mShowTouches) {
1480             writeShowTouchesOptions();
1481         } else if (preference == mShowScreenUpdates) {
1482             writeShowUpdatesOption();
1483         } else if (preference == mDisableOverlays) {
1484             writeDisableOverlaysOption();
1485         } else if (preference == mShowCpuUsage) {
1486             writeCpuUsageOptions();
1487         } else if (preference == mImmediatelyDestroyActivities) {
1488             writeImmediatelyDestroyActivitiesOptions();
1489         } else if (preference == mShowAllANRs) {
1490             writeShowAllANRsOptions();
1491         } else if (preference == mWebViewDataReductionProxy) {
1492             writeWebViewDataReductionProxyOptions();
1493         } else if (preference == mForceHardwareUi) {
1494             writeHardwareUiOptions();
1495         } else if (preference == mForceMsaa) {
1496             writeMsaaOptions();
1497         } else if (preference == mShowHwScreenUpdates) {
1498             writeShowHwScreenUpdatesOptions();
1499         } else if (preference == mShowHwLayersUpdates) {
1500             writeShowHwLayersUpdatesOptions();
1501         } else if (preference == mDebugLayout) {
1502             writeDebugLayoutOptions();
1503         } else if (preference == mForceRtlLayout) {
1504             writeForceRtlOptions();
1505         } else if (preference == mWifiDisplayCertification) {
1506             writeWifiDisplayCertificationOptions();
1507         } else if (preference == mWifiVerboseLogging) {
1508             writeWifiVerboseLoggingOptions();
1509         } else if (preference == mWifiAggressiveHandover) {
1510             writeWifiAggressiveHandoverOptions();
1511         } else if (preference == mWifiAllowScansWithTraffic) {
1512             writeWifiAllowScansWithTrafficOptions();
1513         } else if (preference == mUseNuplayer) {
1514             writeUseNuplayerOptions();
1515         } else if (preference == mUSBAudio) {
1516             writeUSBAudioOptions();
1517         } else {
1518             return super.onPreferenceTreeClick(preferenceScreen, preference);
1519         }
1520
1521         return false;
1522     }
1523
1524     @Override
1525     public boolean onPreferenceChange(Preference preference, Object newValue) {
1526         if (HDCP_CHECKING_KEY.equals(preference.getKey())) {
1527             SystemProperties.set(HDCP_CHECKING_PROPERTY, newValue.toString());
1528             updateHdcpValues();
1529             pokeSystemProperties();
1530             return true;
1531         } else if (preference == mLogdSize) {
1532             writeLogdSizeOption(newValue);
1533             return true;
1534         } else if (preference == mWindowAnimationScale) {
1535             writeAnimationScaleOption(0, mWindowAnimationScale, newValue);
1536             return true;
1537         } else if (preference == mTransitionAnimationScale) {
1538             writeAnimationScaleOption(1, mTransitionAnimationScale, newValue);
1539             return true;
1540         } else if (preference == mAnimatorDurationScale) {
1541             writeAnimationScaleOption(2, mAnimatorDurationScale, newValue);
1542             return true;
1543         } else if (preference == mOverlayDisplayDevices) {
1544             writeOverlayDisplayDevicesOptions(newValue);
1545             return true;
1546         } else if (preference == mOpenGLTraces) {
1547             writeOpenGLTracesOptions(newValue);
1548             return true;
1549         } else if (preference == mTrackFrameTime) {
1550             writeTrackFrameTimeOptions(newValue);
1551             return true;
1552         } else if (preference == mDebugHwOverdraw) {
1553             writeDebugHwOverdrawOptions(newValue);
1554             return true;
1555         } else if (preference == mShowNonRectClip) {
1556             writeShowNonRectClipOptions(newValue);
1557             return true;
1558         } else if (preference == mAppProcessLimit) {
1559             writeAppProcessLimitOptions(newValue);
1560             return true;
1561         } else if (preference == mSimulateColorSpace) {
1562             writeSimulateColorSpace(newValue);
1563             return true;
1564         }
1565         return false;
1566     }
1567
1568     private void dismissDialogs() {
1569         if (mAdbDialog != null) {
1570             mAdbDialog.dismiss();
1571             mAdbDialog = null;
1572         }
1573         if (mAdbKeysDialog != null) {
1574             mAdbKeysDialog.dismiss();
1575             mAdbKeysDialog = null;
1576         }
1577         if (mEnableDialog != null) {
1578             mEnableDialog.dismiss();
1579             mEnableDialog = null;
1580         }
1581     }
1582
1583     public void onClick(DialogInterface dialog, int which) {
1584         if (dialog == mAdbDialog) {
1585             if (which == DialogInterface.BUTTON_POSITIVE) {
1586                 mDialogClicked = true;
1587                 Settings.Global.putInt(getActivity().getContentResolver(),
1588                         Settings.Global.ADB_ENABLED, 1);
1589                 mVerifyAppsOverUsb.setEnabled(true);
1590                 updateVerifyAppsOverUsbOptions();
1591                 updateBugreportOptions();
1592             } else {
1593                 // Reset the toggle
1594                 mEnableAdb.setChecked(false);
1595             }
1596         } else if (dialog == mAdbKeysDialog) {
1597             if (which == DialogInterface.BUTTON_POSITIVE) {
1598                 try {
1599                     IBinder b = ServiceManager.getService(Context.USB_SERVICE);
1600                     IUsbManager service = IUsbManager.Stub.asInterface(b);
1601                     service.clearUsbDebuggingKeys();
1602                 } catch (RemoteException e) {
1603                     Log.e(TAG, "Unable to clear adb keys", e);
1604                 }
1605             }
1606         } else if (dialog == mEnableDialog) {
1607             if (which == DialogInterface.BUTTON_POSITIVE) {
1608                 mDialogClicked = true;
1609                 Settings.Global.putInt(getActivity().getContentResolver(),
1610                         Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 1);
1611                 mLastEnabledState = true;
1612                 setPrefsEnabledState(mLastEnabledState);
1613             } else {
1614                 // Reset the toggle
1615                 mSwitchBar.setChecked(false);
1616             }
1617         }
1618     }
1619
1620     public void onDismiss(DialogInterface dialog) {
1621         // Assuming that onClick gets called first
1622         if (dialog == mAdbDialog) {
1623             if (!mDialogClicked) {
1624                 mEnableAdb.setChecked(false);
1625             }
1626             mAdbDialog = null;
1627         } else if (dialog == mEnableDialog) {
1628             if (!mDialogClicked) {
1629                 mSwitchBar.setChecked(false);
1630             }
1631             mEnableDialog = null;
1632         }
1633     }
1634
1635     @Override
1636     public void onDestroy() {
1637         dismissDialogs();
1638         super.onDestroy();
1639     }
1640
1641     void pokeSystemProperties() {
1642         if (!mDontPokeProperties) {
1643             //noinspection unchecked
1644             (new SystemPropPoker()).execute();
1645         }
1646     }
1647
1648     static class SystemPropPoker extends AsyncTask<Void, Void, Void> {
1649         @Override
1650         protected Void doInBackground(Void... params) {
1651             String[] services;
1652             try {
1653                 services = ServiceManager.listServices();
1654             } catch (RemoteException e) {
1655                 return null;
1656             }
1657             for (String service : services) {
1658                 IBinder obj = ServiceManager.checkService(service);
1659                 if (obj != null) {
1660                     Parcel data = Parcel.obtain();
1661                     try {
1662                         obj.transact(IBinder.SYSPROPS_TRANSACTION, data, null, 0);
1663                     } catch (RemoteException e) {
1664                     } catch (Exception e) {
1665                         Log.i(TAG, "Someone wrote a bad service '" + service
1666                                 + "' that doesn't like to be poked: " + e);
1667                     }
1668                     data.recycle();
1669                 }
1670             }
1671             return null;
1672         }
1673     }
1674
1675     private static boolean isPackageInstalled(Context context, String packageName) {
1676         try {
1677             return context.getPackageManager().getPackageInfo(packageName, 0) != null;
1678         } catch (NameNotFoundException e) {
1679             return false;
1680         }
1681     }
1682
1683     /**
1684      * For Search.
1685      */
1686     public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
1687             new BaseSearchIndexProvider() {
1688
1689                 private boolean isShowingDeveloperOptions(Context context) {
1690                     return context.getSharedPreferences(DevelopmentSettings.PREF_FILE,
1691                             Context.MODE_PRIVATE).getBoolean(
1692                                     DevelopmentSettings.PREF_SHOW,
1693                                     android.os.Build.TYPE.equals("eng"));
1694                 }
1695
1696                 @Override
1697                 public List<SearchIndexableResource> getXmlResourcesToIndex(
1698                         Context context, boolean enabled) {
1699
1700                     if (!isShowingDeveloperOptions(context)) {
1701                         return null;
1702                     }
1703
1704                     final SearchIndexableResource sir = new SearchIndexableResource(context);
1705                     sir.xmlResId = R.xml.development_prefs;
1706                     return Arrays.asList(sir);
1707                 }
1708
1709                 @Override
1710                 public List<String> getNonIndexableKeys(Context context) {
1711                     if (!isShowingDeveloperOptions(context)) {
1712                         return null;
1713                     }
1714
1715                     final List<String> keys = new ArrayList<String>();
1716                     if (!showEnableOemUnlockPreference()) {
1717                         keys.add(ENABLE_OEM_UNLOCK);
1718                     }
1719                     return keys;
1720                 }
1721             };
1722 }