blob: 08bdc422c90ec07ab1db15ae62ffcd2f17e76d51 [file] [log] [blame]
Jason parks8fd5bc92011-01-12 16:03:31 -06001/*
2 * Copyright (C) 2011 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
17package com.android.settings;
18
Jason parks8fd5bc92011-01-12 16:03:31 -060019import android.app.Activity;
Fyodor Kupolov1b5cc422014-12-08 16:13:11 -080020import android.app.ActivityManager;
Jason parks8fd5bc92011-01-12 16:03:31 -060021import android.app.StatusBarManager;
Fyodor Kupolov1b5cc422014-12-08 16:13:11 -080022import android.content.BroadcastReceiver;
Jason parks8fd5bc92011-01-12 16:03:31 -060023import android.content.ComponentName;
24import android.content.Context;
Jason parksec5a45e2011-01-18 15:28:36 -060025import android.content.Intent;
Paul Lawrence7ae20e32014-07-22 15:00:50 -070026import android.content.pm.ActivityInfo;
Jason parks8fd5bc92011-01-12 16:03:31 -060027import android.content.pm.PackageManager;
Paul Lawrence7ae20e32014-07-22 15:00:50 -070028import android.content.res.Resources.NotFoundException;
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -070029import android.media.AudioManager;
Jason parks06c5ff42011-03-01 10:17:40 -060030import android.os.AsyncTask;
Jason parks8fd5bc92011-01-12 16:03:31 -060031import android.os.Bundle;
Jason parksec5a45e2011-01-18 15:28:36 -060032import android.os.Handler;
Jason parks8fd5bc92011-01-12 16:03:31 -060033import android.os.IBinder;
Jason parksec5a45e2011-01-18 15:28:36 -060034import android.os.Message;
Jason parks35933812011-01-21 15:48:20 -060035import android.os.PowerManager;
David Brown8373b452011-06-20 12:38:45 -070036import android.os.RemoteException;
Jason parks8fd5bc92011-01-12 16:03:31 -060037import android.os.ServiceManager;
38import android.os.SystemProperties;
Christopher Tate6a5929b2012-09-10 15:39:05 -070039import android.os.UserHandle;
Jason parks8fd5bc92011-01-12 16:03:31 -060040import android.os.storage.IMountService;
Paul Lawrenceb05f39d2014-02-04 10:22:19 -080041import android.os.storage.StorageManager;
Vikram Aggarwal6ebbd302012-05-04 14:09:52 -070042import android.provider.Settings;
Tyler Gunn3e71b192014-09-10 15:21:33 -070043import android.telecom.TelecomManager;
David Brown8373b452011-06-20 12:38:45 -070044import android.telephony.TelephonyManager;
Vikram Aggarwald1147252012-05-08 13:52:30 -070045import android.text.Editable;
Jason parksec5a45e2011-01-18 15:28:36 -060046import android.text.TextUtils;
Vikram Aggarwald1147252012-05-08 13:52:30 -070047import android.text.TextWatcher;
Paul Lawrenceb15c68f2014-06-05 07:24:23 -070048import android.text.format.DateUtils;
Jason parks8fd5bc92011-01-12 16:03:31 -060049import android.util.Log;
50import android.view.KeyEvent;
Vikram Aggarwald1147252012-05-08 13:52:30 -070051import android.view.MotionEvent;
Andy Stadler13d62042011-01-31 19:21:37 -080052import android.view.View;
Jim Millerfb3d5ca2013-11-14 14:40:22 -080053import android.view.WindowManager;
Andy Stadler13d62042011-01-31 19:21:37 -080054import android.view.View.OnClickListener;
Vikram Aggarwald1147252012-05-08 13:52:30 -070055import android.view.View.OnKeyListener;
56import android.view.View.OnTouchListener;
Jason parks8fd5bc92011-01-12 16:03:31 -060057import android.view.inputmethod.EditorInfo;
Ben Komalo9fcb6a72011-08-26 14:40:18 -070058import android.view.inputmethod.InputMethodInfo;
Jason parks75c085e2011-02-10 14:03:47 -060059import android.view.inputmethod.InputMethodManager;
Ben Komalo9fcb6a72011-08-26 14:40:18 -070060import android.view.inputmethod.InputMethodSubtype;
Andy Stadler13d62042011-01-31 19:21:37 -080061import android.widget.Button;
Jason parksec5a45e2011-01-18 15:28:36 -060062import android.widget.EditText;
63import android.widget.ProgressBar;
Jason parks8fd5bc92011-01-12 16:03:31 -060064import android.widget.TextView;
65
Wink Saville55434042012-06-14 12:33:43 -070066import com.android.internal.telephony.PhoneConstants;
Paul Lawrenceb05f39d2014-02-04 10:22:19 -080067import com.android.internal.widget.LockPatternUtils;
68import com.android.internal.widget.LockPatternView;
69import com.android.internal.widget.LockPatternView.Cell;
Ben Komalo9fcb6a72011-08-26 14:40:18 -070070
Paul Lawrencef6cda3b2014-06-12 08:26:08 -070071import static com.android.internal.widget.LockPatternView.DisplayMode;
72
Ben Komalo9fcb6a72011-08-26 14:40:18 -070073import java.util.List;
Ben Komalo91a2f052011-08-16 17:48:25 -070074
75/**
76 * Settings screens to show the UI flows for encrypting/decrypting the device.
77 *
78 * This may be started via adb for debugging the UI layout, without having to go through
79 * encryption flows everytime. It should be noted that starting the activity in this manner
80 * is only useful for verifying UI-correctness - the behavior will not be identical.
81 * <pre>
82 * $ adb shell pm enable com.android.settings/.CryptKeeper
83 * $ adb shell am start \
84 * -e "com.android.settings.CryptKeeper.DEBUG_FORCE_VIEW" "progress" \
85 * -n com.android.settings/.CryptKeeper
86 * </pre>
87 */
Vikram Aggarwald1147252012-05-08 13:52:30 -070088public class CryptKeeper extends Activity implements TextView.OnEditorActionListener,
89 OnKeyListener, OnTouchListener, TextWatcher {
Jason parksec5a45e2011-01-18 15:28:36 -060090 private static final String TAG = "CryptKeeper";
Jason parks35933812011-01-21 15:48:20 -060091
Jason parks8fd5bc92011-01-12 16:03:31 -060092 private static final String DECRYPT_STATE = "trigger_restart_framework";
Paul Crowley51e08112014-11-12 12:06:38 +000093
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -070094 /** Message sent to us to indicate encryption update progress. */
95 private static final int MESSAGE_UPDATE_PROGRESS = 1;
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -070096 /** Message sent to us to indicate alerting the user that we are waiting for password entry */
Paul Crowley51e08112014-11-12 12:06:38 +000097 private static final int MESSAGE_NOTIFY = 2;
Jason parksec5a45e2011-01-18 15:28:36 -060098
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -070099 // Constants used to control policy.
Paul Crowley13b8b562014-11-21 09:43:17 +0000100 private static final int MAX_FAILED_ATTEMPTS = 30;
Jason parksec5a45e2011-01-18 15:28:36 -0600101 private static final int COOL_DOWN_ATTEMPTS = 10;
Jason parksec5a45e2011-01-18 15:28:36 -0600102
David Brown8373b452011-06-20 12:38:45 -0700103 // Intent action for launching the Emergency Dialer activity.
104 static final String ACTION_EMERGENCY_DIAL = "com.android.phone.EmergencyDialer.DIAL";
105
Ben Komalo91a2f052011-08-16 17:48:25 -0700106 // Debug Intent extras so that this Activity may be started via adb for debugging UI layouts
107 private static final String EXTRA_FORCE_VIEW =
108 "com.android.settings.CryptKeeper.DEBUG_FORCE_VIEW";
109 private static final String FORCE_VIEW_PROGRESS = "progress";
Ben Komalo91a2f052011-08-16 17:48:25 -0700110 private static final String FORCE_VIEW_ERROR = "error";
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700111 private static final String FORCE_VIEW_PASSWORD = "password";
Ben Komalo91a2f052011-08-16 17:48:25 -0700112
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700113 /** When encryption is detected, this flag indicates whether or not we've checked for errors. */
Ben Komalo0e666092011-09-01 15:42:00 -0700114 private boolean mValidationComplete;
Ben Komalod4758ef2011-09-08 14:36:08 -0700115 private boolean mValidationRequested;
Ben Komalo0e666092011-09-01 15:42:00 -0700116 /** A flag to indicate that the volume is in a bad state (e.g. partially encrypted). */
117 private boolean mEncryptionGoneBad;
Paul Lawrence87abbd32014-08-28 15:56:38 -0700118 /** If gone bad, should we show encryption failed (false) or corrupt (true)*/
119 private boolean mCorrupt;
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700120 /** A flag to indicate when the back event should be ignored */
121 private boolean mIgnoreBack = false;
Paul Crowley51e08112014-11-12 12:06:38 +0000122 /** When set, blocks unlocking. Set every COOL_DOWN_ATTEMPTS attempts, only cleared
123 by power cycling phone. */
124 private boolean mCooldown = false;
125
Andy Stadler14997402011-02-01 15:34:59 -0800126 PowerManager.WakeLock mWakeLock;
Jason parks06c5ff42011-03-01 10:17:40 -0600127 private EditText mPasswordEntry;
Paul Lawrenceb05f39d2014-02-04 10:22:19 -0800128 private LockPatternView mLockPatternView;
Vikram Aggarwald1147252012-05-08 13:52:30 -0700129 /** Number of calls to {@link #notifyUser()} to ignore before notifying. */
130 private int mNotificationCountdown = 0;
Paul Lawrence73456ac2014-05-16 07:56:04 -0700131 /** Number of calls to {@link #notifyUser()} before we release the wakelock */
132 private int mReleaseWakeLockCountdown = 0;
Paul Lawrence5a70f052014-06-13 11:09:55 -0700133 private int mStatusString = R.string.enter_password;
Andy Stadler14997402011-02-01 15:34:59 -0800134
Paul Lawrencef6cda3b2014-06-12 08:26:08 -0700135 // how long we wait to clear a wrong pattern
136 private static final int WRONG_PATTERN_CLEAR_TIMEOUT_MS = 1500;
137
Paul Lawrence0f11e152014-08-20 07:43:32 -0700138 // how long we wait to clear a right pattern
139 private static final int RIGHT_PATTERN_CLEAR_TIMEOUT_MS = 500;
140
Paul Crowley2555e5f2014-11-07 00:52:57 -0800141 // When the user enters a short pin/password, run this to show an error,
142 // but don't count it against attempts.
143 private final Runnable mFakeUnlockAttemptRunnable = new Runnable() {
Paul Crowley51e08112014-11-12 12:06:38 +0000144 @Override
Paul Crowley2555e5f2014-11-07 00:52:57 -0800145 public void run() {
146 handleBadAttempt(1 /* failedAttempt */);
147 }
148 };
149
150 // TODO: this should be tuned to match minimum decryption timeout
151 private static final int FAKE_ATTEMPT_DELAY = 1000;
152
153 private final Runnable mClearPatternRunnable = new Runnable() {
Paul Crowley529834d2014-10-21 10:12:47 +0100154 @Override
Paul Lawrencef6cda3b2014-06-12 08:26:08 -0700155 public void run() {
156 mLockPatternView.clearPattern();
157 }
158 };
159
Andy Stadler14997402011-02-01 15:34:59 -0800160 /**
161 * Used to propagate state through configuration changes (e.g. screen rotation)
162 */
163 private static class NonConfigurationInstanceState {
164 final PowerManager.WakeLock wakelock;
165
166 NonConfigurationInstanceState(PowerManager.WakeLock _wakelock) {
167 wakelock = _wakelock;
168 }
169 }
170
Jason parks06c5ff42011-03-01 10:17:40 -0600171 private class DecryptTask extends AsyncTask<String, Void, Integer> {
Paul Lawrenceced7db42014-09-18 11:23:40 -0700172 private void hide(int id) {
173 View view = findViewById(id);
174 if (view != null) {
175 view.setVisibility(View.GONE);
176 }
177 }
178
Jason parks06c5ff42011-03-01 10:17:40 -0600179 @Override
Paul Crowley529834d2014-10-21 10:12:47 +0100180 protected void onPreExecute() {
181 super.onPreExecute();
Paul Crowley2555e5f2014-11-07 00:52:57 -0800182 beginAttempt();
Paul Crowley529834d2014-10-21 10:12:47 +0100183 }
184
185 @Override
Jason parks06c5ff42011-03-01 10:17:40 -0600186 protected Integer doInBackground(String... params) {
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700187 final IMountService service = getMountService();
Jason parks06c5ff42011-03-01 10:17:40 -0600188 try {
189 return service.decryptStorage(params[0]);
190 } catch (Exception e) {
191 Log.e(TAG, "Error while decrypting...", e);
192 return -1;
193 }
194 }
195
196 @Override
197 protected void onPostExecute(Integer failedAttempts) {
198 if (failedAttempts == 0) {
Paul Lawrence89c75702014-07-11 07:34:44 -0700199 // The password was entered successfully. Simply do nothing
200 // and wait for the service restart to switch to surfacefligner
Paul Lawrence0f11e152014-08-20 07:43:32 -0700201 if (mLockPatternView != null) {
202 mLockPatternView.removeCallbacks(mClearPatternRunnable);
203 mLockPatternView.postDelayed(mClearPatternRunnable, RIGHT_PATTERN_CLEAR_TIMEOUT_MS);
204 }
Paul Crowley529834d2014-10-21 10:12:47 +0100205 final TextView status = (TextView) findViewById(R.id.status);
206 status.setText(R.string.starting_android);
Paul Lawrenceced7db42014-09-18 11:23:40 -0700207 hide(R.id.passwordEntry);
208 hide(R.id.switch_ime_button);
209 hide(R.id.lockPattern);
Paul Lawrenceced7db42014-09-18 11:23:40 -0700210 hide(R.id.owner_info);
211 hide(R.id.emergencyCallButton);
Jason parks06c5ff42011-03-01 10:17:40 -0600212 } else if (failedAttempts == MAX_FAILED_ATTEMPTS) {
213 // Factory reset the device.
Jeff Sharkey1de688d2014-09-24 13:57:07 -0700214 Intent intent = new Intent(Intent.ACTION_MASTER_CLEAR);
215 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
216 intent.putExtra(Intent.EXTRA_REASON, "CryptKeeper.MAX_FAILED_ATTEMPTS");
217 sendBroadcast(intent);
Paul Lawrence384d8e52014-08-08 15:11:36 -0700218 } else if (failedAttempts == -1) {
219 // Right password, but decryption failed. Tell user bad news ...
220 setContentView(R.layout.crypt_keeper_progress);
221 showFactoryReset(true);
222 return;
Jason parks06c5ff42011-03-01 10:17:40 -0600223 } else {
Paul Crowley2555e5f2014-11-07 00:52:57 -0800224 handleBadAttempt(failedAttempts);
225 }
226 }
227 }
228
229 private void beginAttempt() {
230 final TextView status = (TextView) findViewById(R.id.status);
231 status.setText(R.string.checking_decryption);
232 }
233
234 private void handleBadAttempt(Integer failedAttempts) {
235 // Wrong entry. Handle pattern case.
236 if (mLockPatternView != null) {
237 mLockPatternView.setDisplayMode(DisplayMode.Wrong);
238 mLockPatternView.removeCallbacks(mClearPatternRunnable);
239 mLockPatternView.postDelayed(mClearPatternRunnable, WRONG_PATTERN_CLEAR_TIMEOUT_MS);
240 }
241 if ((failedAttempts % COOL_DOWN_ATTEMPTS) == 0) {
Paul Crowley51e08112014-11-12 12:06:38 +0000242 mCooldown = true;
243 // No need to setBackFunctionality(false) - it's already done
244 // at this point.
Paul Crowley2555e5f2014-11-07 00:52:57 -0800245 cooldown();
246 } else {
247 final TextView status = (TextView) findViewById(R.id.status);
248
249 int remainingAttempts = MAX_FAILED_ATTEMPTS - failedAttempts;
250 if (remainingAttempts < COOL_DOWN_ATTEMPTS) {
251 CharSequence warningTemplate = getText(R.string.crypt_keeper_warn_wipe);
252 CharSequence warning = TextUtils.expandTemplate(warningTemplate,
253 Integer.toString(remainingAttempts));
254 status.setText(warning);
255 } else {
256 int passwordType = StorageManager.CRYPT_TYPE_PASSWORD;
257 try {
258 final IMountService service = getMountService();
259 passwordType = service.getPasswordType();
260 } catch (Exception e) {
261 Log.e(TAG, "Error calling mount service " + e);
Paul Lawrencef6cda3b2014-06-12 08:26:08 -0700262 }
Paul Crowley2555e5f2014-11-07 00:52:57 -0800263
264 if (passwordType == StorageManager.CRYPT_TYPE_PIN) {
265 status.setText(R.string.cryptkeeper_wrong_pin);
266 } else if (passwordType == StorageManager.CRYPT_TYPE_PATTERN) {
267 status.setText(R.string.cryptkeeper_wrong_pattern);
Paul Lawrencef6cda3b2014-06-12 08:26:08 -0700268 } else {
Paul Crowley2555e5f2014-11-07 00:52:57 -0800269 status.setText(R.string.cryptkeeper_wrong_password);
Paul Lawrence2daf2642014-03-14 09:20:24 -0700270 }
Jason parks06c5ff42011-03-01 10:17:40 -0600271 }
Paul Crowley2555e5f2014-11-07 00:52:57 -0800272
273 if (mLockPatternView != null) {
274 mLockPatternView.setDisplayMode(DisplayMode.Wrong);
275 mLockPatternView.setEnabled(true);
276 }
277
278 // Reenable the password entry
279 if (mPasswordEntry != null) {
280 mPasswordEntry.setEnabled(true);
281 final InputMethodManager imm = (InputMethodManager) getSystemService(
282 Context.INPUT_METHOD_SERVICE);
283 imm.showSoftInput(mPasswordEntry, 0);
284 setBackFunctionality(true);
285 }
Jason parks06c5ff42011-03-01 10:17:40 -0600286 }
287 }
Jason parks75c085e2011-02-10 14:03:47 -0600288
Ben Komalo0e666092011-09-01 15:42:00 -0700289 private class ValidationTask extends AsyncTask<Void, Void, Boolean> {
Paul Lawrence87abbd32014-08-28 15:56:38 -0700290 int state;
291
Ben Komalo0e666092011-09-01 15:42:00 -0700292 @Override
293 protected Boolean doInBackground(Void... params) {
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700294 final IMountService service = getMountService();
Ben Komalo0e666092011-09-01 15:42:00 -0700295 try {
Ben Komalod4758ef2011-09-08 14:36:08 -0700296 Log.d(TAG, "Validating encryption state.");
Paul Lawrence87abbd32014-08-28 15:56:38 -0700297 state = service.getEncryptionState();
Ben Komalo0e666092011-09-01 15:42:00 -0700298 if (state == IMountService.ENCRYPTION_STATE_NONE) {
299 Log.w(TAG, "Unexpectedly in CryptKeeper even though there is no encryption.");
300 return true; // Unexpected, but fine, I guess...
301 }
302 return state == IMountService.ENCRYPTION_STATE_OK;
303 } catch (RemoteException e) {
304 Log.w(TAG, "Unable to get encryption state properly");
305 return true;
306 }
307 }
308
309 @Override
310 protected void onPostExecute(Boolean result) {
311 mValidationComplete = true;
312 if (Boolean.FALSE.equals(result)) {
313 Log.w(TAG, "Incomplete, or corrupted encryption detected. Prompting user to wipe.");
314 mEncryptionGoneBad = true;
Paul Lawrence87abbd32014-08-28 15:56:38 -0700315 mCorrupt = state == IMountService.ENCRYPTION_STATE_ERROR_CORRUPT;
Ben Komalod4758ef2011-09-08 14:36:08 -0700316 } else {
317 Log.d(TAG, "Encryption state validated. Proceeding to configure UI");
Ben Komalo0e666092011-09-01 15:42:00 -0700318 }
319 setupUi();
320 }
321 }
322
Ben Komalo91a2f052011-08-16 17:48:25 -0700323 private final Handler mHandler = new Handler() {
Jason parksec5a45e2011-01-18 15:28:36 -0600324 @Override
325 public void handleMessage(Message msg) {
Jason parksec5a45e2011-01-18 15:28:36 -0600326 switch (msg.what) {
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700327 case MESSAGE_UPDATE_PROGRESS:
Jason parksf8217302011-01-26 13:11:42 -0600328 updateProgress();
Jason parksec5a45e2011-01-18 15:28:36 -0600329 break;
Jason parks35933812011-01-21 15:48:20 -0600330
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700331 case MESSAGE_NOTIFY:
332 notifyUser();
333 break;
Jason parksec5a45e2011-01-18 15:28:36 -0600334 }
335 }
336 };
Jason parks35933812011-01-21 15:48:20 -0600337
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700338 private AudioManager mAudioManager;
Vikram Aggarwalbf459da2012-11-08 16:54:59 -0800339 /** The status bar where back/home/recent buttons are shown. */
340 private StatusBarManager mStatusBar;
341
342 /** All the widgets to disable in the status bar */
343 final private static int sWidgetsToDisable = StatusBarManager.DISABLE_EXPAND
344 | StatusBarManager.DISABLE_NOTIFICATION_ICONS
345 | StatusBarManager.DISABLE_NOTIFICATION_ALERTS
346 | StatusBarManager.DISABLE_SYSTEM_INFO
347 | StatusBarManager.DISABLE_HOME
Alon Albert66d050b2013-09-30 17:08:12 -0700348 | StatusBarManager.DISABLE_SEARCH
Vikram Aggarwalbf459da2012-11-08 16:54:59 -0800349 | StatusBarManager.DISABLE_RECENT;
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700350
Paul Crowley2555e5f2014-11-07 00:52:57 -0800351 protected static final int MIN_LENGTH_BEFORE_REPORT = LockPatternUtils.MIN_LOCK_PATTERN_SIZE;
352
Ben Komalo91a2f052011-08-16 17:48:25 -0700353 /** @return whether or not this Activity was started for debugging the UI only. */
354 private boolean isDebugView() {
355 return getIntent().hasExtra(EXTRA_FORCE_VIEW);
356 }
357
358 /** @return whether or not this Activity was started for debugging the specific UI view only. */
359 private boolean isDebugView(String viewType /* non-nullable */) {
360 return viewType.equals(getIntent().getStringExtra(EXTRA_FORCE_VIEW));
361 }
362
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700363 /**
364 * Notify the user that we are awaiting input. Currently this sends an audio alert.
365 */
366 private void notifyUser() {
Vikram Aggarwald1147252012-05-08 13:52:30 -0700367 if (mNotificationCountdown > 0) {
Vikram Aggarwald1147252012-05-08 13:52:30 -0700368 --mNotificationCountdown;
369 } else if (mAudioManager != null) {
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700370 try {
371 // Play the standard keypress sound at full volume. This should be available on
372 // every device. We cannot play a ringtone here because media services aren't
373 // available yet. A DTMF-style tone is too soft to be noticed, and might not exist
374 // on tablet devices. The idea is to alert the user that something is needed: this
375 // does not have to be pleasing.
376 mAudioManager.playSoundEffect(AudioManager.FX_KEYPRESS_STANDARD, 100);
377 } catch (Exception e) {
378 Log.w(TAG, "notifyUser: Exception while playing sound: " + e);
379 }
380 }
Vikram Aggarwal86b93932012-05-01 16:46:06 -0700381 // Notify the user again in 5 seconds.
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700382 mHandler.removeMessages(MESSAGE_NOTIFY);
Vikram Aggarwal86b93932012-05-01 16:46:06 -0700383 mHandler.sendEmptyMessageDelayed(MESSAGE_NOTIFY, 5 * 1000);
Paul Lawrence73456ac2014-05-16 07:56:04 -0700384
385 if (mWakeLock.isHeld()) {
386 if (mReleaseWakeLockCountdown > 0) {
387 --mReleaseWakeLockCountdown;
388 } else {
389 mWakeLock.release();
390 }
391 }
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700392 }
393
394 /**
395 * Ignore back events after the user has entered the decrypt screen and while the device is
396 * encrypting.
397 */
398 @Override
399 public void onBackPressed() {
Vikram Aggarwalbf459da2012-11-08 16:54:59 -0800400 // In the rare case that something pressed back even though we were disabled.
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700401 if (mIgnoreBack)
402 return;
403 super.onBackPressed();
404 }
405
Jason parks8fd5bc92011-01-12 16:03:31 -0600406 @Override
407 public void onCreate(Bundle savedInstanceState) {
408 super.onCreate(savedInstanceState);
Jason parks35933812011-01-21 15:48:20 -0600409
Andy Stadler95974062011-02-01 17:35:20 -0800410 // If we are not encrypted or encrypting, get out quickly.
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700411 final String state = SystemProperties.get("vold.decrypt");
Ben Komalo91a2f052011-08-16 17:48:25 -0700412 if (!isDebugView() && ("".equals(state) || DECRYPT_STATE.equals(state))) {
Fyodor Kupolov1b5cc422014-12-08 16:13:11 -0800413 disableCryptKeeperComponent(this);
Dianne Hackborn140f6c62011-10-16 11:49:00 -0700414 // Typically CryptKeeper is launched as the home app. We didn't
Dianne Hackborn644fa422011-10-18 13:38:03 -0700415 // want to be running, so need to finish this activity. We can count
416 // on the activity manager re-launching the new home app upon finishing
417 // this one, since this will leave the activity stack empty.
Dianne Hackborn140f6c62011-10-16 11:49:00 -0700418 // NOTE: This is really grungy. I think it would be better for the
419 // activity manager to explicitly launch the crypt keeper instead of
420 // home in the situation where we need to decrypt the device
421 finish();
Jason parks8fd5bc92011-01-12 16:03:31 -0600422 return;
423 }
Jason parks35933812011-01-21 15:48:20 -0600424
Paul Lawrence7ae20e32014-07-22 15:00:50 -0700425 try {
426 if (getResources().getBoolean(R.bool.crypt_keeper_allow_rotation)) {
427 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
428 }
429 } catch (NotFoundException e) {
430 }
431
Vikram Aggarwalb96b35a2012-05-01 11:09:39 -0700432 // Disable the status bar, but do NOT disable back because the user needs a way to go
433 // from keyboard settings and back to the password screen.
Vikram Aggarwalbf459da2012-11-08 16:54:59 -0800434 mStatusBar = (StatusBarManager) getSystemService(Context.STATUS_BAR_SERVICE);
435 mStatusBar.disable(sWidgetsToDisable);
Andy Stadler14997402011-02-01 15:34:59 -0800436
Vikram Aggarwalea1186d2012-05-03 15:35:03 -0700437 setAirplaneModeIfNecessary();
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700438 mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
Andy Stadler14997402011-02-01 15:34:59 -0800439 // Check for (and recover) retained instance data
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700440 final Object lastInstance = getLastNonConfigurationInstance();
Andy Stadler14997402011-02-01 15:34:59 -0800441 if (lastInstance instanceof NonConfigurationInstanceState) {
442 NonConfigurationInstanceState retained = (NonConfigurationInstanceState) lastInstance;
443 mWakeLock = retained.wakelock;
Ben Komalo04606752011-08-18 14:50:26 -0700444 Log.d(TAG, "Restoring wakelock from NonConfigurationInstanceState");
Andy Stadler14997402011-02-01 15:34:59 -0800445 }
Jason parksec5a45e2011-01-18 15:28:36 -0600446 }
Jason parks35933812011-01-21 15:48:20 -0600447
Andy Stadler95974062011-02-01 17:35:20 -0800448 /**
449 * Note, we defer the state check and screen setup to onStart() because this will be
450 * re-run if the user clicks the power button (sleeping/waking the screen), and this is
451 * especially important if we were to lose the wakelock for any reason.
452 */
453 @Override
454 public void onStart() {
455 super.onStart();
Ben Komalod4758ef2011-09-08 14:36:08 -0700456 setupUi();
Ben Komalo0e666092011-09-01 15:42:00 -0700457 }
458
459 /**
460 * Initializes the UI based on the current state of encryption.
461 * This is idempotent - calling repeatedly will simply re-initialize the UI.
462 */
463 private void setupUi() {
464 if (mEncryptionGoneBad || isDebugView(FORCE_VIEW_ERROR)) {
465 setContentView(R.layout.crypt_keeper_progress);
Paul Lawrence87abbd32014-08-28 15:56:38 -0700466 showFactoryReset(mCorrupt);
Ben Komalo0e666092011-09-01 15:42:00 -0700467 return;
468 }
469
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700470 final String progress = SystemProperties.get("vold.encrypt_progress");
Ben Komalo0e666092011-09-01 15:42:00 -0700471 if (!"".equals(progress) || isDebugView(FORCE_VIEW_PROGRESS)) {
Andy Stadler95974062011-02-01 17:35:20 -0800472 setContentView(R.layout.crypt_keeper_progress);
473 encryptionProgressInit();
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700474 } else if (mValidationComplete || isDebugView(FORCE_VIEW_PASSWORD)) {
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700475 new AsyncTask<Void, Void, Void>() {
Paul Crowley529834d2014-10-21 10:12:47 +0100476 int passwordType = StorageManager.CRYPT_TYPE_PASSWORD;
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700477 String owner_info;
Paul Lawrence0f11e152014-08-20 07:43:32 -0700478 boolean pattern_visible;
Paul Lawrenceb05f39d2014-02-04 10:22:19 -0800479
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700480 @Override
481 public Void doInBackground(Void... v) {
482 try {
483 final IMountService service = getMountService();
Paul Crowley529834d2014-10-21 10:12:47 +0100484 passwordType = service.getPasswordType();
Elliott Hughesf9d6d292014-10-02 13:29:58 -0700485 owner_info = service.getField(StorageManager.OWNER_INFO_KEY);
486 pattern_visible = !("0".equals(service.getField(StorageManager.PATTERN_VISIBLE_KEY)));
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700487 } catch (Exception e) {
488 Log.e(TAG, "Error calling mount service " + e);
489 }
490
491 return null;
492 }
493
494 @Override
495 public void onPostExecute(java.lang.Void v) {
Paul Crowley51e08112014-11-12 12:06:38 +0000496 if (passwordType == StorageManager.CRYPT_TYPE_PIN) {
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700497 setContentView(R.layout.crypt_keeper_pin_entry);
Paul Lawrence5a70f052014-06-13 11:09:55 -0700498 mStatusString = R.string.enter_pin;
Paul Crowley529834d2014-10-21 10:12:47 +0100499 } else if (passwordType == StorageManager.CRYPT_TYPE_PATTERN) {
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700500 setContentView(R.layout.crypt_keeper_pattern_entry);
501 setBackFunctionality(false);
Paul Lawrence5a70f052014-06-13 11:09:55 -0700502 mStatusString = R.string.enter_pattern;
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700503 } else {
504 setContentView(R.layout.crypt_keeper_password_entry);
Paul Lawrence5a70f052014-06-13 11:09:55 -0700505 mStatusString = R.string.enter_password;
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700506 }
Paul Lawrence5a70f052014-06-13 11:09:55 -0700507 final TextView status = (TextView) findViewById(R.id.status);
508 status.setText(mStatusString);
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700509
Paul Lawrence5a70f052014-06-13 11:09:55 -0700510 final TextView ownerInfo = (TextView) findViewById(R.id.owner_info);
511 ownerInfo.setText(owner_info);
512 ownerInfo.setSelected(true); // Required for marquee'ing to work
513
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700514 passwordEntryInit();
Paul Lawrence5a70f052014-06-13 11:09:55 -0700515
Paul Lawrence0f11e152014-08-20 07:43:32 -0700516 if (mLockPatternView != null) {
517 mLockPatternView.setInStealthMode(!pattern_visible);
518 }
Paul Crowley51e08112014-11-12 12:06:38 +0000519 if (mCooldown) {
520 // in case we are cooling down and coming back from emergency dialler
Paul Lawrence5a70f052014-06-13 11:09:55 -0700521 setBackFunctionality(false);
Paul Crowley51e08112014-11-12 12:06:38 +0000522 cooldown();
Paul Lawrence5a70f052014-06-13 11:09:55 -0700523 }
Paul Crowley51e08112014-11-12 12:06:38 +0000524
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700525 }
526 }.execute();
Ben Komalod4758ef2011-09-08 14:36:08 -0700527 } else if (!mValidationRequested) {
528 // We're supposed to be encrypted, but no validation has been done.
529 new ValidationTask().execute((Void[]) null);
530 mValidationRequested = true;
Andy Stadler95974062011-02-01 17:35:20 -0800531 }
532 }
533
Jason parksf8217302011-01-26 13:11:42 -0600534 @Override
535 public void onStop() {
536 super.onStop();
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700537 mHandler.removeMessages(MESSAGE_UPDATE_PROGRESS);
538 mHandler.removeMessages(MESSAGE_NOTIFY);
Andy Stadler14997402011-02-01 15:34:59 -0800539 }
540
541 /**
542 * Reconfiguring, so propagate the wakelock to the next instance. This runs between onStop()
543 * and onDestroy() and only if we are changing configuration (e.g. rotation). Also clears
544 * mWakeLock so the subsequent call to onDestroy does not release it.
545 */
546 @Override
547 public Object onRetainNonConfigurationInstance() {
548 NonConfigurationInstanceState state = new NonConfigurationInstanceState(mWakeLock);
Ben Komalo04606752011-08-18 14:50:26 -0700549 Log.d(TAG, "Handing wakelock off to NonConfigurationInstanceState");
Andy Stadler14997402011-02-01 15:34:59 -0800550 mWakeLock = null;
551 return state;
552 }
553
554 @Override
555 public void onDestroy() {
556 super.onDestroy();
Jason parksf8217302011-01-26 13:11:42 -0600557
558 if (mWakeLock != null) {
Ben Komalo04606752011-08-18 14:50:26 -0700559 Log.d(TAG, "Releasing and destroying wakelock");
Jason parksf8217302011-01-26 13:11:42 -0600560 mWakeLock.release();
561 mWakeLock = null;
562 }
563 }
564
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700565 /**
566 * Start encrypting the device.
567 */
Jason parksec5a45e2011-01-18 15:28:36 -0600568 private void encryptionProgressInit() {
Jason parks35933812011-01-21 15:48:20 -0600569 // Accquire a partial wakelock to prevent the device from sleeping. Note
570 // we never release this wakelock as we will be restarted after the device
571 // is encrypted.
Ben Komalo04606752011-08-18 14:50:26 -0700572 Log.d(TAG, "Encryption progress screen initializing.");
Ben Komalo9ee164f2011-09-21 10:40:50 -0700573 if (mWakeLock == null) {
Ben Komalo04606752011-08-18 14:50:26 -0700574 Log.d(TAG, "Acquiring wakelock.");
575 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
576 mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);
577 mWakeLock.acquire();
578 }
Jason parks35933812011-01-21 15:48:20 -0600579
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700580 ((ProgressBar) findViewById(R.id.progress_bar)).setIndeterminate(true);
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700581 // Ignore all back presses from now, both hard and soft keys.
Vikram Aggarwalbf459da2012-11-08 16:54:59 -0800582 setBackFunctionality(false);
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700583 // Start the first run of progress manually. This method sets up messages to occur at
584 // repeated intervals.
Jason parksf8217302011-01-26 13:11:42 -0600585 updateProgress();
586 }
587
Paul Lawrence384d8e52014-08-08 15:11:36 -0700588 /**
589 * Show factory reset screen allowing the user to reset their phone when
590 * there is nothing else we can do
591 * @param corrupt true if userdata is corrupt, false if encryption failed
592 * partway through
593 */
Jeff Sharkey1de688d2014-09-24 13:57:07 -0700594 private void showFactoryReset(final boolean corrupt) {
Andy Stadler13d62042011-01-31 19:21:37 -0800595 // Hide the encryption-bot to make room for the "factory reset" button
596 findViewById(R.id.encroid).setVisibility(View.GONE);
597
598 // Show the reset button, failure text, and a divider
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700599 final Button button = (Button) findViewById(R.id.factory_reset);
Andy Stadler13d62042011-01-31 19:21:37 -0800600 button.setVisibility(View.VISIBLE);
601 button.setOnClickListener(new OnClickListener() {
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700602 @Override
Andy Stadler13d62042011-01-31 19:21:37 -0800603 public void onClick(View v) {
604 // Factory reset the device.
Jeff Sharkey1de688d2014-09-24 13:57:07 -0700605 Intent intent = new Intent(Intent.ACTION_MASTER_CLEAR);
606 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
607 intent.putExtra(Intent.EXTRA_REASON,
608 "CryptKeeper.showFactoryReset() corrupt=" + corrupt);
609 sendBroadcast(intent);
Andy Stadler13d62042011-01-31 19:21:37 -0800610 }
611 });
612
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700613 // Alert the user of the failure.
Paul Lawrence384d8e52014-08-08 15:11:36 -0700614 if (corrupt) {
615 ((TextView) findViewById(R.id.title)).setText(R.string.crypt_keeper_data_corrupt_title);
616 ((TextView) findViewById(R.id.status)).setText(R.string.crypt_keeper_data_corrupt_summary);
617 } else {
618 ((TextView) findViewById(R.id.title)).setText(R.string.crypt_keeper_failed_title);
619 ((TextView) findViewById(R.id.status)).setText(R.string.crypt_keeper_failed_summary);
620 }
Andy Stadler13d62042011-01-31 19:21:37 -0800621
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700622 final View view = findViewById(R.id.bottom_divider);
623 // TODO(viki): Why would the bottom divider be missing in certain layouts? Investigate.
Ben Komalof0104df2011-08-16 17:48:42 -0700624 if (view != null) {
625 view.setVisibility(View.VISIBLE);
626 }
Andy Stadler13d62042011-01-31 19:21:37 -0800627 }
628
Jason parksf8217302011-01-26 13:11:42 -0600629 private void updateProgress() {
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700630 final String state = SystemProperties.get("vold.encrypt_progress");
Jason parksf8217302011-01-26 13:11:42 -0600631
Ben Komalo0e666092011-09-01 15:42:00 -0700632 if ("error_partially_encrypted".equals(state)) {
Paul Lawrence384d8e52014-08-08 15:11:36 -0700633 showFactoryReset(false);
Andy Stadler13d62042011-01-31 19:21:37 -0800634 return;
635 }
636
Paul Lawrenceb15c68f2014-06-05 07:24:23 -0700637 // Get status as percentage first
638 CharSequence status = getText(R.string.crypt_keeper_setup_description);
639 int percent = 0;
Jason parksf8217302011-01-26 13:11:42 -0600640 try {
Ben Komalo91a2f052011-08-16 17:48:25 -0700641 // Force a 50% progress state when debugging the view.
Paul Lawrenceb15c68f2014-06-05 07:24:23 -0700642 percent = isDebugView() ? 50 : Integer.parseInt(state);
Jason parksf8217302011-01-26 13:11:42 -0600643 } catch (Exception e) {
644 Log.w(TAG, "Error parsing progress: " + e.toString());
645 }
Paul Lawrenceb15c68f2014-06-05 07:24:23 -0700646 String progress = Integer.toString(percent);
Jason parksf8217302011-01-26 13:11:42 -0600647
Paul Lawrenceb15c68f2014-06-05 07:24:23 -0700648 // Now try to get status as time remaining and replace as appropriate
Ben Komalo04606752011-08-18 14:50:26 -0700649 Log.v(TAG, "Encryption progress: " + progress);
Paul Lawrenceb15c68f2014-06-05 07:24:23 -0700650 try {
651 final String timeProperty = SystemProperties.get("vold.encrypt_time_remaining");
652 int time = Integer.parseInt(timeProperty);
653 if (time >= 0) {
654 // Round up to multiple of 10 - this way display is less jerky
655 time = (time + 9) / 10 * 10;
656 progress = DateUtils.formatElapsedTime(time);
657 status = getText(R.string.crypt_keeper_setup_time_remaining);
658 }
659 } catch (Exception e) {
660 // Will happen if no time etc - show percentage
661 }
662
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700663 final TextView tv = (TextView) findViewById(R.id.status);
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700664 if (tv != null) {
Paul Lawrenceb15c68f2014-06-05 07:24:23 -0700665 tv.setText(TextUtils.expandTemplate(status, progress));
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700666 }
Paul Lawrenceb15c68f2014-06-05 07:24:23 -0700667
668 // Check the progress every 1 seconds
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700669 mHandler.removeMessages(MESSAGE_UPDATE_PROGRESS);
Paul Lawrenceb15c68f2014-06-05 07:24:23 -0700670 mHandler.sendEmptyMessageDelayed(MESSAGE_UPDATE_PROGRESS, 1000);
Jason parksf8217302011-01-26 13:11:42 -0600671 }
672
Paul Crowley51e08112014-11-12 12:06:38 +0000673 /** Insist on a power cycle to force the user to waste time between retries.
674 *
675 * Call setBackFunctionality(false) before calling this. */
Jason parksf8217302011-01-26 13:11:42 -0600676 private void cooldown() {
Paul Crowley51e08112014-11-12 12:06:38 +0000677 // Disable the password entry.
678 if (mPasswordEntry != null) {
679 mPasswordEntry.setEnabled(false);
Jason parksf8217302011-01-26 13:11:42 -0600680 }
Paul Crowley51e08112014-11-12 12:06:38 +0000681 if (mLockPatternView != null) {
682 mLockPatternView.setEnabled(false);
683 }
684
685 final TextView status = (TextView) findViewById(R.id.status);
686 status.setText(R.string.crypt_keeper_force_power_cycle);
Jason parksec5a45e2011-01-18 15:28:36 -0600687 }
Jason parks35933812011-01-21 15:48:20 -0600688
Vikram Aggarwalbf459da2012-11-08 16:54:59 -0800689 /**
690 * Sets the back status: enabled or disabled according to the parameter.
691 * @param isEnabled true if back is enabled, false otherwise.
692 */
693 private final void setBackFunctionality(boolean isEnabled) {
694 mIgnoreBack = !isEnabled;
695 if (isEnabled) {
696 mStatusBar.disable(sWidgetsToDisable);
697 } else {
698 mStatusBar.disable(sWidgetsToDisable | StatusBarManager.DISABLE_BACK);
699 }
700 }
701
Paul Crowley2555e5f2014-11-07 00:52:57 -0800702 private void fakeUnlockAttempt(View postingView) {
703 beginAttempt();
704 postingView.postDelayed(mFakeUnlockAttemptRunnable, FAKE_ATTEMPT_DELAY);
705 }
706
Paul Lawrenceb05f39d2014-02-04 10:22:19 -0800707 protected LockPatternView.OnPatternListener mChooseNewLockPatternListener =
Paul Lawrencef6cda3b2014-06-12 08:26:08 -0700708 new LockPatternView.OnPatternListener() {
Paul Lawrenceb05f39d2014-02-04 10:22:19 -0800709
Paul Lawrencef6cda3b2014-06-12 08:26:08 -0700710 @Override
711 public void onPatternStart() {
712 mLockPatternView.removeCallbacks(mClearPatternRunnable);
713 }
Paul Lawrenceb05f39d2014-02-04 10:22:19 -0800714
Paul Lawrencef6cda3b2014-06-12 08:26:08 -0700715 @Override
716 public void onPatternCleared() {
717 }
Paul Lawrenceb05f39d2014-02-04 10:22:19 -0800718
Paul Lawrencef6cda3b2014-06-12 08:26:08 -0700719 @Override
720 public void onPatternDetected(List<LockPatternView.Cell> pattern) {
721 mLockPatternView.setEnabled(false);
Paul Crowley2555e5f2014-11-07 00:52:57 -0800722 if (pattern.size() >= MIN_LENGTH_BEFORE_REPORT) {
723 new DecryptTask().execute(LockPatternUtils.patternToString(pattern));
724 } else {
725 // Allow user to make as many of these as they want.
726 fakeUnlockAttempt(mLockPatternView);
727 }
Paul Lawrencef6cda3b2014-06-12 08:26:08 -0700728 }
Paul Lawrenceb05f39d2014-02-04 10:22:19 -0800729
Paul Lawrencef6cda3b2014-06-12 08:26:08 -0700730 @Override
731 public void onPatternCellAdded(List<Cell> pattern) {
732 }
Paul Lawrenceb05f39d2014-02-04 10:22:19 -0800733 };
734
735 private void passwordEntryInit() {
736 // Password/pin case
Jason parks06c5ff42011-03-01 10:17:40 -0600737 mPasswordEntry = (EditText) findViewById(R.id.passwordEntry);
Paul Lawrenceb05f39d2014-02-04 10:22:19 -0800738 if (mPasswordEntry != null){
739 mPasswordEntry.setOnEditorActionListener(this);
740 mPasswordEntry.requestFocus();
741 // Become quiet when the user interacts with the Edit text screen.
742 mPasswordEntry.setOnKeyListener(this);
743 mPasswordEntry.setOnTouchListener(this);
744 mPasswordEntry.addTextChangedListener(this);
745 }
746
747 // Pattern case
748 mLockPatternView = (LockPatternView) findViewById(R.id.lockPattern);
749 if (mLockPatternView != null) {
750 mLockPatternView.setOnPatternListener(mChooseNewLockPatternListener);
751 }
Jason parks35933812011-01-21 15:48:20 -0600752
Vikram Aggarwalc62d3212012-05-02 16:29:10 -0700753 // Disable the Emergency call button if the device has no voice telephone capability
Santos Cordon3afbdf02014-05-29 21:48:16 -0700754 if (!getTelephonyManager().isVoiceCapable()) {
Vikram Aggarwalc62d3212012-05-02 16:29:10 -0700755 final View emergencyCall = findViewById(R.id.emergencyCallButton);
756 if (emergencyCall != null) {
757 Log.d(TAG, "Removing the emergency Call button");
758 emergencyCall.setVisibility(View.GONE);
759 }
760 }
761
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700762 final View imeSwitcher = findViewById(R.id.switch_ime_button);
Ben Komalo9fcb6a72011-08-26 14:40:18 -0700763 final InputMethodManager imm = (InputMethodManager) getSystemService(
764 Context.INPUT_METHOD_SERVICE);
765 if (imeSwitcher != null && hasMultipleEnabledIMEsOrSubtypes(imm, false)) {
766 imeSwitcher.setVisibility(View.VISIBLE);
767 imeSwitcher.setOnClickListener(new OnClickListener() {
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700768 @Override
Ben Komalo9fcb6a72011-08-26 14:40:18 -0700769 public void onClick(View v) {
770 imm.showInputMethodPicker();
771 }
772 });
Jason parks00046d62011-06-13 17:38:45 -0500773 }
David Brown8373b452011-06-20 12:38:45 -0700774
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700775 // We want to keep the screen on while waiting for input. In minimal boot mode, the device
776 // is completely non-functional, and we want the user to notice the device and enter a
777 // password.
778 if (mWakeLock == null) {
779 Log.d(TAG, "Acquiring wakelock.");
780 final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
781 if (pm != null) {
782 mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);
783 mWakeLock.acquire();
Paul Lawrence73456ac2014-05-16 07:56:04 -0700784 // Keep awake for 10 minutes - if the user hasn't been alerted by then
785 // best not to just drain their battery
Paul Lawrence5a70f052014-06-13 11:09:55 -0700786 mReleaseWakeLockCountdown = 96; // 96 * 5 secs per click + 120 secs before we show this = 600
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700787 }
788 }
Paul Lawrence73456ac2014-05-16 07:56:04 -0700789
Ben Komalo9fcb6a72011-08-26 14:40:18 -0700790 // Asynchronously throw up the IME, since there are issues with requesting it to be shown
791 // immediately.
Paul Crowley51e08112014-11-12 12:06:38 +0000792 if (mLockPatternView == null && !mCooldown) {
Paul Lawrencee54e9322014-03-13 14:05:48 -0700793 mHandler.postDelayed(new Runnable() {
794 @Override public void run() {
795 imm.showSoftInputUnchecked(0, null);
796 }
797 }, 0);
798 }
Ben Komalo9fcb6a72011-08-26 14:40:18 -0700799
David Brown8373b452011-06-20 12:38:45 -0700800 updateEmergencyCallButtonState();
Vikram Aggarwald1147252012-05-08 13:52:30 -0700801 // Notify the user in 120 seconds that we are waiting for him to enter the password.
Vikram Aggarwal86b93932012-05-01 16:46:06 -0700802 mHandler.removeMessages(MESSAGE_NOTIFY);
Vikram Aggarwald1147252012-05-08 13:52:30 -0700803 mHandler.sendEmptyMessageDelayed(MESSAGE_NOTIFY, 120 * 1000);
Jim Millerfb3d5ca2013-11-14 14:40:22 -0800804
John Spurlock2c526512014-09-17 12:55:17 -0400805 // Dismiss secure & non-secure keyguards while this screen is showing.
806 getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
807 | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
Jason parks8fd5bc92011-01-12 16:03:31 -0600808 }
809
Ben Komalo9fcb6a72011-08-26 14:40:18 -0700810 /**
811 * Method adapted from com.android.inputmethod.latin.Utils
812 *
813 * @param imm The input method manager
814 * @param shouldIncludeAuxiliarySubtypes
815 * @return true if we have multiple IMEs to choose from
816 */
817 private boolean hasMultipleEnabledIMEsOrSubtypes(InputMethodManager imm,
818 final boolean shouldIncludeAuxiliarySubtypes) {
819 final List<InputMethodInfo> enabledImis = imm.getEnabledInputMethodList();
820
821 // Number of the filtered IMEs
822 int filteredImisCount = 0;
823
824 for (InputMethodInfo imi : enabledImis) {
825 // We can return true immediately after we find two or more filtered IMEs.
826 if (filteredImisCount > 1) return true;
827 final List<InputMethodSubtype> subtypes =
828 imm.getEnabledInputMethodSubtypeList(imi, true);
829 // IMEs that have no subtypes should be counted.
830 if (subtypes.isEmpty()) {
831 ++filteredImisCount;
832 continue;
833 }
834
835 int auxCount = 0;
836 for (InputMethodSubtype subtype : subtypes) {
837 if (subtype.isAuxiliary()) {
838 ++auxCount;
839 }
840 }
841 final int nonAuxCount = subtypes.size() - auxCount;
842
843 // IMEs that have one or more non-auxiliary subtypes should be counted.
844 // If shouldIncludeAuxiliarySubtypes is true, IMEs that have two or more auxiliary
845 // subtypes should be counted as well.
846 if (nonAuxCount > 0 || (shouldIncludeAuxiliarySubtypes && auxCount > 1)) {
847 ++filteredImisCount;
848 continue;
849 }
850 }
851
852 return filteredImisCount > 1
853 // imm.getEnabledInputMethodSubtypeList(null, false) will return the current IME's enabled
854 // input method subtype (The current IME should be LatinIME.)
855 || imm.getEnabledInputMethodSubtypeList(null, false).size() > 1;
856 }
857
Jason parks8fd5bc92011-01-12 16:03:31 -0600858 private IMountService getMountService() {
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700859 final IBinder service = ServiceManager.getService("mount");
Jason parks8fd5bc92011-01-12 16:03:31 -0600860 if (service != null) {
861 return IMountService.Stub.asInterface(service);
862 }
863 return null;
864 }
865
866 @Override
867 public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
Jason parks00046d62011-06-13 17:38:45 -0500868 if (actionId == EditorInfo.IME_NULL || actionId == EditorInfo.IME_ACTION_DONE) {
Jason parks8fd5bc92011-01-12 16:03:31 -0600869 // Get the password
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700870 final String password = v.getText().toString();
Jason parks8fd5bc92011-01-12 16:03:31 -0600871
Jason parksec5a45e2011-01-18 15:28:36 -0600872 if (TextUtils.isEmpty(password)) {
873 return true;
874 }
Jason parks35933812011-01-21 15:48:20 -0600875
Jason parks8fd5bc92011-01-12 16:03:31 -0600876 // Now that we have the password clear the password field.
877 v.setText(null);
878
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700879 // Disable the password entry and back keypress while checking the password. These
880 // we either be re-enabled if the password was wrong or after the cooldown period.
Jason parks06c5ff42011-03-01 10:17:40 -0600881 mPasswordEntry.setEnabled(false);
Vikram Aggarwalbf459da2012-11-08 16:54:59 -0800882 setBackFunctionality(false);
Jason parks8fd5bc92011-01-12 16:03:31 -0600883
Paul Crowley2555e5f2014-11-07 00:52:57 -0800884 if (password.length() >= LockPatternUtils.MIN_LOCK_PATTERN_SIZE) {
885 new DecryptTask().execute(password);
886 } else {
887 // Allow user to make as many of these as they want.
888 fakeUnlockAttempt(mPasswordEntry);
889 }
Jason parks35933812011-01-21 15:48:20 -0600890
Jason parks8fd5bc92011-01-12 16:03:31 -0600891 return true;
892 }
893 return false;
894 }
David Brown8373b452011-06-20 12:38:45 -0700895
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700896 /**
Vikram Aggarwalea1186d2012-05-03 15:35:03 -0700897 * Set airplane mode on the device if it isn't an LTE device.
898 * Full story: In minimal boot mode, we cannot save any state. In particular, we cannot save
899 * any incoming SMS's. So SMSs that are received here will be silently dropped to the floor.
900 * That is bad. Also, we cannot receive any telephone calls in this state. So to avoid
901 * both these problems, we turn the radio off. However, on certain networks turning on and
902 * off the radio takes a long time. In such cases, we are better off leaving the radio
903 * running so the latency of an E911 call is short.
904 * The behavior after this is:
905 * 1. Emergency dialing: the emergency dialer has logic to force the device out of
906 * airplane mode and restart the radio.
907 * 2. Full boot: we read the persistent settings from the previous boot and restore the
908 * radio to whatever it was before it restarted. This also happens when rebooting a
909 * phone that has no encryption.
910 */
911 private final void setAirplaneModeIfNecessary() {
912 final boolean isLteDevice =
Santos Cordon3afbdf02014-05-29 21:48:16 -0700913 getTelephonyManager().getLteOnCdmaMode() == PhoneConstants.LTE_ON_CDMA_TRUE;
Vikram Aggarwalea1186d2012-05-03 15:35:03 -0700914 if (!isLteDevice) {
915 Log.d(TAG, "Going into airplane mode.");
Christopher Tate6a5929b2012-09-10 15:39:05 -0700916 Settings.Global.putInt(getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 1);
Vikram Aggarwalea1186d2012-05-03 15:35:03 -0700917 final Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
918 intent.putExtra("state", true);
Christopher Tate6a5929b2012-09-10 15:39:05 -0700919 sendBroadcastAsUser(intent, UserHandle.ALL);
Vikram Aggarwalea1186d2012-05-03 15:35:03 -0700920 }
921 }
922
923 /**
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700924 * Code to update the state of, and handle clicks from, the "Emergency call" button.
925 *
926 * This code is mostly duplicated from the corresponding code in
927 * LockPatternUtils and LockPatternKeyguardView under frameworks/base.
928 */
David Brown8373b452011-06-20 12:38:45 -0700929 private void updateEmergencyCallButtonState() {
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700930 final Button emergencyCall = (Button) findViewById(R.id.emergencyCallButton);
David Brown8373b452011-06-20 12:38:45 -0700931 // The button isn't present at all in some configurations.
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700932 if (emergencyCall == null)
933 return;
David Brown8373b452011-06-20 12:38:45 -0700934
935 if (isEmergencyCallCapable()) {
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700936 emergencyCall.setVisibility(View.VISIBLE);
937 emergencyCall.setOnClickListener(new View.OnClickListener() {
938 @Override
939
David Brown8373b452011-06-20 12:38:45 -0700940 public void onClick(View v) {
941 takeEmergencyCallAction();
942 }
943 });
944 } else {
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700945 emergencyCall.setVisibility(View.GONE);
David Brown8373b452011-06-20 12:38:45 -0700946 return;
947 }
948
David Brown8373b452011-06-20 12:38:45 -0700949 int textId;
Tyler Gunn3e71b192014-09-10 15:21:33 -0700950 if (getTelecomManager().isInCall()) {
Paul Lawrence89c75702014-07-11 07:34:44 -0700951 // Show "return to call"
David Brown8373b452011-06-20 12:38:45 -0700952 textId = R.string.cryptkeeper_return_to_call;
David Brown8373b452011-06-20 12:38:45 -0700953 } else {
954 textId = R.string.cryptkeeper_emergency_call;
David Brown8373b452011-06-20 12:38:45 -0700955 }
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700956 emergencyCall.setText(textId);
David Brown8373b452011-06-20 12:38:45 -0700957 }
958
959 private boolean isEmergencyCallCapable() {
960 return getResources().getBoolean(com.android.internal.R.bool.config_voice_capable);
961 }
962
963 private void takeEmergencyCallAction() {
Tyler Gunn3e71b192014-09-10 15:21:33 -0700964 TelecomManager telecomManager = getTelecomManager();
965 if (telecomManager.isInCall()) {
966 telecomManager.showInCallScreen(false /* showDialpad */);
David Brown8373b452011-06-20 12:38:45 -0700967 } else {
968 launchEmergencyDialer();
969 }
970 }
971
David Brown8373b452011-06-20 12:38:45 -0700972
973 private void launchEmergencyDialer() {
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700974 final Intent intent = new Intent(ACTION_EMERGENCY_DIAL);
David Brown8373b452011-06-20 12:38:45 -0700975 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
976 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
Paul Lawrence5a70f052014-06-13 11:09:55 -0700977 setBackFunctionality(true);
David Brown8373b452011-06-20 12:38:45 -0700978 startActivity(intent);
979 }
Vikram Aggarwald1147252012-05-08 13:52:30 -0700980
Santos Cordon3afbdf02014-05-29 21:48:16 -0700981 private TelephonyManager getTelephonyManager() {
982 return (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
983 }
984
Tyler Gunn3e71b192014-09-10 15:21:33 -0700985 private TelecomManager getTelecomManager() {
986 return (TelecomManager) getSystemService(Context.TELECOM_SERVICE);
Santos Cordon35230e92014-07-07 16:25:10 -0700987 }
988
Vikram Aggarwald1147252012-05-08 13:52:30 -0700989 /**
990 * Listen to key events so we can disable sounds when we get a keyinput in EditText.
991 */
992 private void delayAudioNotification() {
Vikram Aggarwald1147252012-05-08 13:52:30 -0700993 mNotificationCountdown = 20;
994 }
995
996 @Override
997 public boolean onKey(View v, int keyCode, KeyEvent event) {
998 delayAudioNotification();
999 return false;
1000 }
1001
1002 @Override
1003 public boolean onTouch(View v, MotionEvent event) {
1004 delayAudioNotification();
1005 return false;
1006 }
1007
1008 @Override
1009 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
1010 return;
1011 }
1012
1013 @Override
1014 public void onTextChanged(CharSequence s, int start, int before, int count) {
1015 delayAudioNotification();
1016 }
1017
1018 @Override
1019 public void afterTextChanged(Editable s) {
1020 return;
1021 }
Fyodor Kupolov1b5cc422014-12-08 16:13:11 -08001022
1023 private static void disableCryptKeeperComponent(Context context) {
1024 PackageManager pm = context.getPackageManager();
1025 ComponentName name = new ComponentName(context, CryptKeeper.class);
1026 Log.d(TAG, "Disabling component " + name);
1027 pm.setComponentEnabledSetting(name, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
1028 PackageManager.DONT_KILL_APP);
1029 }
1030
1031 public static class UserInitBroadcastReceiver extends BroadcastReceiver {
1032
1033 @Override
1034 public void onReceive(Context context, Intent intent) {
1035 final String intentAction = intent.getAction();
1036 // Disable CryptKeeper activity if user is not primary
1037 if (Intent.ACTION_USER_INITIALIZE.equals(intentAction)
1038 && UserHandle.USER_OWNER != UserHandle.myUserId()) {
1039 disableCryptKeeperComponent(context);
1040 }
1041 }
1042 }
David Brown8373b452011-06-20 12:38:45 -07001043}