OSDN Git Service

Merge "Changing wifi connection dialog per UX"
[android-x86/packages-apps-Settings.git] / src / com / android / settings / SecuritySettings.java
1 /*
2  * Copyright (C) 2007 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
20 import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
21
22 import android.app.AlertDialog;
23 import android.app.admin.DevicePolicyManager;
24 import android.content.Context;
25 import android.content.DialogInterface;
26 import android.content.Intent;
27 import android.os.Bundle;
28 import android.os.Vibrator;
29 import android.preference.CheckBoxPreference;
30 import android.preference.ListPreference;
31 import android.preference.Preference;
32 import android.preference.Preference.OnPreferenceChangeListener;
33 import android.preference.PreferenceGroup;
34 import android.preference.PreferenceScreen;
35 import android.provider.Settings;
36 import android.security.KeyStore;
37 import android.telephony.TelephonyManager;
38 import android.util.Log;
39
40 import com.android.internal.telephony.Phone;
41 import com.android.internal.widget.LockPatternUtils;
42
43 import java.util.ArrayList;
44
45 /**
46  * Gesture lock pattern settings.
47  */
48 public class SecuritySettings extends SettingsPreferenceFragment
49         implements OnPreferenceChangeListener, DialogInterface.OnClickListener {
50
51     // Lock Settings
52     private static final String KEY_UNLOCK_SET_OR_CHANGE = "unlock_set_or_change";
53     private static final String KEY_LOCK_ENABLED = "lockenabled";
54     private static final String KEY_VISIBLE_PATTERN = "visiblepattern";
55     private static final String KEY_TACTILE_FEEDBACK_ENABLED = "unlock_tactile_feedback";
56     private static final String KEY_SECURITY_CATEGORY = "security_category";
57     private static final String KEY_LOCK_AFTER_TIMEOUT = "lock_after_timeout";
58     private static final int SET_OR_CHANGE_LOCK_METHOD_REQUEST = 123;
59
60     // Misc Settings
61     private static final String KEY_SIM_LOCK = "sim_lock";
62     private static final String KEY_SHOW_PASSWORD = "show_password";
63     private static final String KEY_RESET_CREDENTIALS = "reset_credentials";
64     private static final String KEY_TOGGLE_INSTALL_APPLICATIONS = "toggle_install_applications";
65
66     DevicePolicyManager mDPM;
67
68     private ChooseLockSettingsHelper mChooseLockSettingsHelper;
69     private LockPatternUtils mLockPatternUtils;
70     private ListPreference mLockAfter;
71
72     private CheckBoxPreference mVisiblePattern;
73     private CheckBoxPreference mTactileFeedback;
74
75     private CheckBoxPreference mShowPassword;
76
77     private Preference mResetCredentials;
78
79     private CheckBoxPreference mToggleAppInstallation;
80     private DialogInterface mWarnInstallApps;
81
82     @Override
83     public void onCreate(Bundle savedInstanceState) {
84         super.onCreate(savedInstanceState);
85
86         mLockPatternUtils = new LockPatternUtils(getActivity());
87
88         mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
89
90         mChooseLockSettingsHelper = new ChooseLockSettingsHelper(getActivity());
91     }
92
93     private PreferenceScreen createPreferenceHierarchy() {
94         PreferenceScreen root = getPreferenceScreen();
95         if (root != null) {
96             root.removeAll();
97         }
98         addPreferencesFromResource(R.xml.security_settings);
99         root = getPreferenceScreen();
100
101         // Add options for lock/unlock screen
102         int resid = 0;
103         if (!mLockPatternUtils.isSecure()) {
104             if (mLockPatternUtils.isLockScreenDisabled()) {
105                 resid = R.xml.security_settings_lockscreen;
106             } else {
107                 resid = R.xml.security_settings_chooser;
108             }
109         } else {
110             switch (mLockPatternUtils.getKeyguardStoredPasswordQuality()) {
111                 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
112                     resid = R.xml.security_settings_pattern;
113                     break;
114                 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
115                     resid = R.xml.security_settings_pin;
116                     break;
117                 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
118                 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
119                 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
120                     resid = R.xml.security_settings_password;
121                     break;
122             }
123         }
124         addPreferencesFromResource(resid);
125
126
127         // Add options for device encryption
128         DevicePolicyManager dpm =
129                 (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
130
131         switch (dpm.getStorageEncryptionStatus()) {
132         case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
133             // The device is currently encrypted.
134             addPreferencesFromResource(R.xml.security_settings_encrypted);
135             break;
136         case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
137             // This device supports encryption but isn't encrypted.
138             addPreferencesFromResource(R.xml.security_settings_unencrypted);
139             break;
140         }
141
142         // lock after preference
143         mLockAfter = (ListPreference) root.findPreference(KEY_LOCK_AFTER_TIMEOUT);
144         if (mLockAfter != null) {
145             setupLockAfterPreference();
146             updateLockAfterPreferenceSummary();
147         }
148
149         // visible pattern
150         mVisiblePattern = (CheckBoxPreference) root.findPreference(KEY_VISIBLE_PATTERN);
151
152         // tactile feedback. Should be common to all unlock preference screens.
153         mTactileFeedback = (CheckBoxPreference) root.findPreference(KEY_TACTILE_FEEDBACK_ENABLED);
154         if (!((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).hasVibrator()) {
155             PreferenceGroup securityCategory = (PreferenceGroup)
156                     root.findPreference(KEY_SECURITY_CATEGORY);
157             if (securityCategory != null && mTactileFeedback != null) {
158                 securityCategory.removePreference(mTactileFeedback);
159             }
160         }
161
162         // Append the rest of the settings
163         addPreferencesFromResource(R.xml.security_settings_misc);
164
165         // Do not display SIM lock for CDMA phone
166         TelephonyManager tm = TelephonyManager.getDefault();
167         if ((TelephonyManager.PHONE_TYPE_CDMA == tm.getCurrentPhoneType()) &&
168                 (tm.getLteOnCdmaMode() != Phone.LTE_ON_CDMA_TRUE)) {
169             root.removePreference(root.findPreference(KEY_SIM_LOCK));
170         }
171
172         // Show password
173         mShowPassword = (CheckBoxPreference) root.findPreference(KEY_SHOW_PASSWORD);
174
175         // Credential storage
176         mResetCredentials = root.findPreference(KEY_RESET_CREDENTIALS);
177
178         mToggleAppInstallation = (CheckBoxPreference) findPreference(
179                 KEY_TOGGLE_INSTALL_APPLICATIONS);
180         mToggleAppInstallation.setChecked(isNonMarketAppsAllowed());
181
182         return root;
183     }
184
185     private boolean isNonMarketAppsAllowed() {
186         return Settings.Secure.getInt(getContentResolver(),
187                                       Settings.Secure.INSTALL_NON_MARKET_APPS, 0) > 0;
188     }
189
190     private void setNonMarketAppsAllowed(boolean enabled) {
191         // Change the system setting
192         Settings.Secure.putInt(getContentResolver(), Settings.Secure.INSTALL_NON_MARKET_APPS,
193                                 enabled ? 1 : 0);
194     }
195
196     private void warnAppInstallation() {
197         // TODO: DialogFragment?
198         mWarnInstallApps = new AlertDialog.Builder(getActivity()).setTitle(
199                 getResources().getString(R.string.error_title))
200                 .setIcon(com.android.internal.R.drawable.ic_dialog_alert)
201                 .setMessage(getResources().getString(R.string.install_all_warning))
202                 .setPositiveButton(android.R.string.yes, this)
203                 .setNegativeButton(android.R.string.no, null)
204                 .show();
205     }
206
207     public void onClick(DialogInterface dialog, int which) {
208         if (dialog == mWarnInstallApps && which == DialogInterface.BUTTON_POSITIVE) {
209             setNonMarketAppsAllowed(true);
210             mToggleAppInstallation.setChecked(true);
211         }
212     }
213
214     @Override
215     public void onDestroy() {
216         super.onDestroy();
217         if (mWarnInstallApps != null) {
218             mWarnInstallApps.dismiss();
219         }
220     }
221
222     private void setupLockAfterPreference() {
223         // Compatible with pre-Froyo
224         long currentTimeout = Settings.Secure.getLong(getContentResolver(),
225                 Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, 5000);
226         mLockAfter.setValue(String.valueOf(currentTimeout));
227         mLockAfter.setOnPreferenceChangeListener(this);
228         final long adminTimeout = (mDPM != null ? mDPM.getMaximumTimeToLock(null) : 0);
229         final long displayTimeout = Math.max(0,
230                 Settings.System.getInt(getContentResolver(), SCREEN_OFF_TIMEOUT, 0));
231         if (adminTimeout > 0) {
232             // This setting is a slave to display timeout when a device policy is enforced.
233             // As such, maxLockTimeout = adminTimeout - displayTimeout.
234             // If there isn't enough time, shows "immediately" setting.
235             disableUnusableTimeouts(Math.max(0, adminTimeout - displayTimeout));
236         }
237     }
238
239     private void updateLockAfterPreferenceSummary() {
240         // Update summary message with current value
241         long currentTimeout = Settings.Secure.getLong(getContentResolver(),
242                 Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, 5000);
243         final CharSequence[] entries = mLockAfter.getEntries();
244         final CharSequence[] values = mLockAfter.getEntryValues();
245         int best = 0;
246         for (int i = 0; i < values.length; i++) {
247             long timeout = Long.valueOf(values[i].toString());
248             if (currentTimeout >= timeout) {
249                 best = i;
250             }
251         }
252         mLockAfter.setSummary(getString(R.string.lock_after_timeout_summary, entries[best]));
253     }
254
255     private void disableUnusableTimeouts(long maxTimeout) {
256         final CharSequence[] entries = mLockAfter.getEntries();
257         final CharSequence[] values = mLockAfter.getEntryValues();
258         ArrayList<CharSequence> revisedEntries = new ArrayList<CharSequence>();
259         ArrayList<CharSequence> revisedValues = new ArrayList<CharSequence>();
260         for (int i = 0; i < values.length; i++) {
261             long timeout = Long.valueOf(values[i].toString());
262             if (timeout <= maxTimeout) {
263                 revisedEntries.add(entries[i]);
264                 revisedValues.add(values[i]);
265             }
266         }
267         if (revisedEntries.size() != entries.length || revisedValues.size() != values.length) {
268             mLockAfter.setEntries(
269                     revisedEntries.toArray(new CharSequence[revisedEntries.size()]));
270             mLockAfter.setEntryValues(
271                     revisedValues.toArray(new CharSequence[revisedValues.size()]));
272             final int userPreference = Integer.valueOf(mLockAfter.getValue());
273             if (userPreference <= maxTimeout) {
274                 mLockAfter.setValue(String.valueOf(userPreference));
275             } else {
276                 // There will be no highlighted selection since nothing in the list matches
277                 // maxTimeout. The user can still select anything less than maxTimeout.
278                 // TODO: maybe append maxTimeout to the list and mark selected.
279             }
280         }
281         mLockAfter.setEnabled(revisedEntries.size() > 0);
282     }
283
284     @Override
285     public void onResume() {
286         super.onResume();
287
288         // Make sure we reload the preference hierarchy since some of these settings
289         // depend on others...
290         createPreferenceHierarchy();
291
292         final LockPatternUtils lockPatternUtils = mChooseLockSettingsHelper.utils();
293         if (mVisiblePattern != null) {
294             mVisiblePattern.setChecked(lockPatternUtils.isVisiblePatternEnabled());
295         }
296         if (mTactileFeedback != null) {
297             mTactileFeedback.setChecked(lockPatternUtils.isTactileFeedbackEnabled());
298         }
299
300         mShowPassword.setChecked(Settings.System.getInt(getContentResolver(),
301                 Settings.System.TEXT_SHOW_PASSWORD, 1) != 0);
302
303         KeyStore.State state = KeyStore.getInstance().state();
304         mResetCredentials.setEnabled(state != KeyStore.State.UNINITIALIZED);
305     }
306
307     @Override
308     public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
309         final String key = preference.getKey();
310
311         final LockPatternUtils lockPatternUtils = mChooseLockSettingsHelper.utils();
312         if (KEY_UNLOCK_SET_OR_CHANGE.equals(key)) {
313             startFragment(this, "com.android.settings.ChooseLockGeneric$ChooseLockGenericFragment",
314                     SET_OR_CHANGE_LOCK_METHOD_REQUEST, null);
315         } else if (KEY_LOCK_ENABLED.equals(key)) {
316             lockPatternUtils.setLockPatternEnabled(isToggled(preference));
317         } else if (KEY_VISIBLE_PATTERN.equals(key)) {
318             lockPatternUtils.setVisiblePatternEnabled(isToggled(preference));
319         } else if (KEY_TACTILE_FEEDBACK_ENABLED.equals(key)) {
320             lockPatternUtils.setTactileFeedbackEnabled(isToggled(preference));
321         } else if (preference == mShowPassword) {
322             Settings.System.putInt(getContentResolver(), Settings.System.TEXT_SHOW_PASSWORD,
323                     mShowPassword.isChecked() ? 1 : 0);
324         } else if (preference == mToggleAppInstallation) {
325             if (mToggleAppInstallation.isChecked()) {
326                 mToggleAppInstallation.setChecked(false);
327                 warnAppInstallation();
328             } else {
329                 setNonMarketAppsAllowed(false);
330             }
331         } else {
332             // If we didn't handle it, let preferences handle it.
333             return super.onPreferenceTreeClick(preferenceScreen, preference);
334         }
335
336         return true;
337     }
338
339     private boolean isToggled(Preference pref) {
340         return ((CheckBoxPreference) pref).isChecked();
341     }
342
343     /**
344      * see confirmPatternThenDisableAndClear
345      */
346     @Override
347     public void onActivityResult(int requestCode, int resultCode, Intent data) {
348         super.onActivityResult(requestCode, resultCode, data);
349         createPreferenceHierarchy();
350     }
351
352     public boolean onPreferenceChange(Preference preference, Object value) {
353         if (preference == mLockAfter) {
354             int timeout = Integer.parseInt((String) value);
355             try {
356                 Settings.Secure.putInt(getContentResolver(),
357                         Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, timeout);
358             } catch (NumberFormatException e) {
359                 Log.e("SecuritySettings", "could not persist lockAfter timeout setting", e);
360             }
361             updateLockAfterPreferenceSummary();
362         }
363         return true;
364     }
365 }