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