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