OSDN Git Service

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