blob: f386abb7f31ae3d30ed83e28c72a280d4fb9055d [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;
20import android.app.StatusBarManager;
21import android.content.ComponentName;
22import android.content.Context;
Jason parksec5a45e2011-01-18 15:28:36 -060023import android.content.Intent;
Paul Lawrence7ae20e32014-07-22 15:00:50 -070024import android.content.pm.ActivityInfo;
Jason parks8fd5bc92011-01-12 16:03:31 -060025import android.content.pm.PackageManager;
Paul Lawrence7ae20e32014-07-22 15:00:50 -070026import android.content.res.Resources.NotFoundException;
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -070027import android.media.AudioManager;
Jason parks06c5ff42011-03-01 10:17:40 -060028import android.os.AsyncTask;
Jason parks8fd5bc92011-01-12 16:03:31 -060029import android.os.Bundle;
Jason parksec5a45e2011-01-18 15:28:36 -060030import android.os.Handler;
Jason parks8fd5bc92011-01-12 16:03:31 -060031import android.os.IBinder;
Jason parksec5a45e2011-01-18 15:28:36 -060032import android.os.Message;
Jason parks35933812011-01-21 15:48:20 -060033import android.os.PowerManager;
David Brown8373b452011-06-20 12:38:45 -070034import android.os.RemoteException;
Jason parks8fd5bc92011-01-12 16:03:31 -060035import android.os.ServiceManager;
36import android.os.SystemProperties;
Christopher Tate6a5929b2012-09-10 15:39:05 -070037import android.os.UserHandle;
Jason parks8fd5bc92011-01-12 16:03:31 -060038import android.os.storage.IMountService;
Paul Lawrenceb05f39d2014-02-04 10:22:19 -080039import android.os.storage.StorageManager;
Vikram Aggarwal6ebbd302012-05-04 14:09:52 -070040import android.provider.Settings;
Tyler Gunn3e71b192014-09-10 15:21:33 -070041import android.telecom.TelecomManager;
David Brown8373b452011-06-20 12:38:45 -070042import android.telephony.TelephonyManager;
Vikram Aggarwald1147252012-05-08 13:52:30 -070043import android.text.Editable;
Jason parksec5a45e2011-01-18 15:28:36 -060044import android.text.TextUtils;
Vikram Aggarwald1147252012-05-08 13:52:30 -070045import android.text.TextWatcher;
Paul Lawrenceb15c68f2014-06-05 07:24:23 -070046import android.text.format.DateUtils;
Jason parks8fd5bc92011-01-12 16:03:31 -060047import android.util.Log;
48import android.view.KeyEvent;
Vikram Aggarwald1147252012-05-08 13:52:30 -070049import android.view.MotionEvent;
Andy Stadler13d62042011-01-31 19:21:37 -080050import android.view.View;
Jim Millerfb3d5ca2013-11-14 14:40:22 -080051import android.view.WindowManager;
Andy Stadler13d62042011-01-31 19:21:37 -080052import android.view.View.OnClickListener;
Vikram Aggarwald1147252012-05-08 13:52:30 -070053import android.view.View.OnKeyListener;
54import android.view.View.OnTouchListener;
Jason parks8fd5bc92011-01-12 16:03:31 -060055import android.view.inputmethod.EditorInfo;
Ben Komalo9fcb6a72011-08-26 14:40:18 -070056import android.view.inputmethod.InputMethodInfo;
Jason parks75c085e2011-02-10 14:03:47 -060057import android.view.inputmethod.InputMethodManager;
Ben Komalo9fcb6a72011-08-26 14:40:18 -070058import android.view.inputmethod.InputMethodSubtype;
Andy Stadler13d62042011-01-31 19:21:37 -080059import android.widget.Button;
Jason parksec5a45e2011-01-18 15:28:36 -060060import android.widget.EditText;
61import android.widget.ProgressBar;
Jason parks8fd5bc92011-01-12 16:03:31 -060062import android.widget.TextView;
63
Wink Saville55434042012-06-14 12:33:43 -070064import com.android.internal.telephony.PhoneConstants;
Paul Lawrenceb05f39d2014-02-04 10:22:19 -080065import com.android.internal.widget.LockPatternUtils;
66import com.android.internal.widget.LockPatternView;
67import com.android.internal.widget.LockPatternView.Cell;
Ben Komalo9fcb6a72011-08-26 14:40:18 -070068
Paul Lawrencef6cda3b2014-06-12 08:26:08 -070069import static com.android.internal.widget.LockPatternView.DisplayMode;
70
Ben Komalo9fcb6a72011-08-26 14:40:18 -070071import java.util.List;
Ben Komalo91a2f052011-08-16 17:48:25 -070072
73/**
74 * Settings screens to show the UI flows for encrypting/decrypting the device.
75 *
76 * This may be started via adb for debugging the UI layout, without having to go through
77 * encryption flows everytime. It should be noted that starting the activity in this manner
78 * is only useful for verifying UI-correctness - the behavior will not be identical.
79 * <pre>
80 * $ adb shell pm enable com.android.settings/.CryptKeeper
81 * $ adb shell am start \
82 * -e "com.android.settings.CryptKeeper.DEBUG_FORCE_VIEW" "progress" \
83 * -n com.android.settings/.CryptKeeper
84 * </pre>
85 */
Vikram Aggarwald1147252012-05-08 13:52:30 -070086public class CryptKeeper extends Activity implements TextView.OnEditorActionListener,
87 OnKeyListener, OnTouchListener, TextWatcher {
Jason parksec5a45e2011-01-18 15:28:36 -060088 private static final String TAG = "CryptKeeper";
Jason parks35933812011-01-21 15:48:20 -060089
Jason parks8fd5bc92011-01-12 16:03:31 -060090 private static final String DECRYPT_STATE = "trigger_restart_framework";
Paul Crowley51e08112014-11-12 12:06:38 +000091
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -070092 /** Message sent to us to indicate encryption update progress. */
93 private static final int MESSAGE_UPDATE_PROGRESS = 1;
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -070094 /** Message sent to us to indicate alerting the user that we are waiting for password entry */
Paul Crowley51e08112014-11-12 12:06:38 +000095 private static final int MESSAGE_NOTIFY = 2;
Jason parksec5a45e2011-01-18 15:28:36 -060096
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -070097 // Constants used to control policy.
Paul Crowley51e08112014-11-12 12:06:38 +000098 private static final int MAX_FAILED_ATTEMPTS = 100;
Jason parksec5a45e2011-01-18 15:28:36 -060099 private static final int COOL_DOWN_ATTEMPTS = 10;
Jason parksec5a45e2011-01-18 15:28:36 -0600100
David Brown8373b452011-06-20 12:38:45 -0700101 // Intent action for launching the Emergency Dialer activity.
102 static final String ACTION_EMERGENCY_DIAL = "com.android.phone.EmergencyDialer.DIAL";
103
Ben Komalo91a2f052011-08-16 17:48:25 -0700104 // Debug Intent extras so that this Activity may be started via adb for debugging UI layouts
105 private static final String EXTRA_FORCE_VIEW =
106 "com.android.settings.CryptKeeper.DEBUG_FORCE_VIEW";
107 private static final String FORCE_VIEW_PROGRESS = "progress";
Ben Komalo91a2f052011-08-16 17:48:25 -0700108 private static final String FORCE_VIEW_ERROR = "error";
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700109 private static final String FORCE_VIEW_PASSWORD = "password";
Ben Komalo91a2f052011-08-16 17:48:25 -0700110
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700111 /** When encryption is detected, this flag indicates whether or not we've checked for errors. */
Ben Komalo0e666092011-09-01 15:42:00 -0700112 private boolean mValidationComplete;
Ben Komalod4758ef2011-09-08 14:36:08 -0700113 private boolean mValidationRequested;
Ben Komalo0e666092011-09-01 15:42:00 -0700114 /** A flag to indicate that the volume is in a bad state (e.g. partially encrypted). */
115 private boolean mEncryptionGoneBad;
Paul Lawrence87abbd32014-08-28 15:56:38 -0700116 /** If gone bad, should we show encryption failed (false) or corrupt (true)*/
117 private boolean mCorrupt;
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700118 /** A flag to indicate when the back event should be ignored */
119 private boolean mIgnoreBack = false;
Paul Crowley51e08112014-11-12 12:06:38 +0000120 /** When set, blocks unlocking. Set every COOL_DOWN_ATTEMPTS attempts, only cleared
121 by power cycling phone. */
122 private boolean mCooldown = false;
123
Andy Stadler14997402011-02-01 15:34:59 -0800124 PowerManager.WakeLock mWakeLock;
Jason parks06c5ff42011-03-01 10:17:40 -0600125 private EditText mPasswordEntry;
Paul Lawrenceb05f39d2014-02-04 10:22:19 -0800126 private LockPatternView mLockPatternView;
Vikram Aggarwald1147252012-05-08 13:52:30 -0700127 /** Number of calls to {@link #notifyUser()} to ignore before notifying. */
128 private int mNotificationCountdown = 0;
Paul Lawrence73456ac2014-05-16 07:56:04 -0700129 /** Number of calls to {@link #notifyUser()} before we release the wakelock */
130 private int mReleaseWakeLockCountdown = 0;
Paul Lawrence5a70f052014-06-13 11:09:55 -0700131 private int mStatusString = R.string.enter_password;
Andy Stadler14997402011-02-01 15:34:59 -0800132
Paul Lawrencef6cda3b2014-06-12 08:26:08 -0700133 // how long we wait to clear a wrong pattern
134 private static final int WRONG_PATTERN_CLEAR_TIMEOUT_MS = 1500;
135
Paul Lawrence0f11e152014-08-20 07:43:32 -0700136 // how long we wait to clear a right pattern
137 private static final int RIGHT_PATTERN_CLEAR_TIMEOUT_MS = 500;
138
Paul Crowley2555e5f2014-11-07 00:52:57 -0800139 // When the user enters a short pin/password, run this to show an error,
140 // but don't count it against attempts.
141 private final Runnable mFakeUnlockAttemptRunnable = new Runnable() {
Paul Crowley51e08112014-11-12 12:06:38 +0000142 @Override
Paul Crowley2555e5f2014-11-07 00:52:57 -0800143 public void run() {
144 handleBadAttempt(1 /* failedAttempt */);
145 }
146 };
147
148 // TODO: this should be tuned to match minimum decryption timeout
149 private static final int FAKE_ATTEMPT_DELAY = 1000;
150
151 private final Runnable mClearPatternRunnable = new Runnable() {
Paul Crowley529834d2014-10-21 10:12:47 +0100152 @Override
Paul Lawrencef6cda3b2014-06-12 08:26:08 -0700153 public void run() {
154 mLockPatternView.clearPattern();
155 }
156 };
157
Andy Stadler14997402011-02-01 15:34:59 -0800158 /**
159 * Used to propagate state through configuration changes (e.g. screen rotation)
160 */
161 private static class NonConfigurationInstanceState {
162 final PowerManager.WakeLock wakelock;
163
164 NonConfigurationInstanceState(PowerManager.WakeLock _wakelock) {
165 wakelock = _wakelock;
166 }
167 }
168
Jason parks06c5ff42011-03-01 10:17:40 -0600169 private class DecryptTask extends AsyncTask<String, Void, Integer> {
Paul Lawrenceced7db42014-09-18 11:23:40 -0700170 private void hide(int id) {
171 View view = findViewById(id);
172 if (view != null) {
173 view.setVisibility(View.GONE);
174 }
175 }
176
Jason parks06c5ff42011-03-01 10:17:40 -0600177 @Override
Paul Crowley529834d2014-10-21 10:12:47 +0100178 protected void onPreExecute() {
179 super.onPreExecute();
Paul Crowley2555e5f2014-11-07 00:52:57 -0800180 beginAttempt();
Paul Crowley529834d2014-10-21 10:12:47 +0100181 }
182
183 @Override
Jason parks06c5ff42011-03-01 10:17:40 -0600184 protected Integer doInBackground(String... params) {
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700185 final IMountService service = getMountService();
Jason parks06c5ff42011-03-01 10:17:40 -0600186 try {
187 return service.decryptStorage(params[0]);
188 } catch (Exception e) {
189 Log.e(TAG, "Error while decrypting...", e);
190 return -1;
191 }
192 }
193
194 @Override
195 protected void onPostExecute(Integer failedAttempts) {
196 if (failedAttempts == 0) {
Paul Lawrence89c75702014-07-11 07:34:44 -0700197 // The password was entered successfully. Simply do nothing
198 // and wait for the service restart to switch to surfacefligner
Paul Lawrence0f11e152014-08-20 07:43:32 -0700199 if (mLockPatternView != null) {
200 mLockPatternView.removeCallbacks(mClearPatternRunnable);
201 mLockPatternView.postDelayed(mClearPatternRunnable, RIGHT_PATTERN_CLEAR_TIMEOUT_MS);
202 }
Paul Crowley529834d2014-10-21 10:12:47 +0100203 final TextView status = (TextView) findViewById(R.id.status);
204 status.setText(R.string.starting_android);
Paul Lawrenceced7db42014-09-18 11:23:40 -0700205 hide(R.id.passwordEntry);
206 hide(R.id.switch_ime_button);
207 hide(R.id.lockPattern);
Paul Lawrenceced7db42014-09-18 11:23:40 -0700208 hide(R.id.owner_info);
209 hide(R.id.emergencyCallButton);
Jason parks06c5ff42011-03-01 10:17:40 -0600210 } else if (failedAttempts == MAX_FAILED_ATTEMPTS) {
211 // Factory reset the device.
Jeff Sharkey1de688d2014-09-24 13:57:07 -0700212 Intent intent = new Intent(Intent.ACTION_MASTER_CLEAR);
213 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
214 intent.putExtra(Intent.EXTRA_REASON, "CryptKeeper.MAX_FAILED_ATTEMPTS");
215 sendBroadcast(intent);
Paul Lawrence384d8e52014-08-08 15:11:36 -0700216 } else if (failedAttempts == -1) {
217 // Right password, but decryption failed. Tell user bad news ...
218 setContentView(R.layout.crypt_keeper_progress);
219 showFactoryReset(true);
220 return;
Jason parks06c5ff42011-03-01 10:17:40 -0600221 } else {
Paul Crowley2555e5f2014-11-07 00:52:57 -0800222 handleBadAttempt(failedAttempts);
223 }
224 }
225 }
226
227 private void beginAttempt() {
228 final TextView status = (TextView) findViewById(R.id.status);
229 status.setText(R.string.checking_decryption);
230 }
231
232 private void handleBadAttempt(Integer failedAttempts) {
233 // Wrong entry. Handle pattern case.
234 if (mLockPatternView != null) {
235 mLockPatternView.setDisplayMode(DisplayMode.Wrong);
236 mLockPatternView.removeCallbacks(mClearPatternRunnable);
237 mLockPatternView.postDelayed(mClearPatternRunnable, WRONG_PATTERN_CLEAR_TIMEOUT_MS);
238 }
239 if ((failedAttempts % COOL_DOWN_ATTEMPTS) == 0) {
Paul Crowley51e08112014-11-12 12:06:38 +0000240 mCooldown = true;
241 // No need to setBackFunctionality(false) - it's already done
242 // at this point.
Paul Crowley2555e5f2014-11-07 00:52:57 -0800243 cooldown();
244 } else {
245 final TextView status = (TextView) findViewById(R.id.status);
246
247 int remainingAttempts = MAX_FAILED_ATTEMPTS - failedAttempts;
248 if (remainingAttempts < COOL_DOWN_ATTEMPTS) {
249 CharSequence warningTemplate = getText(R.string.crypt_keeper_warn_wipe);
250 CharSequence warning = TextUtils.expandTemplate(warningTemplate,
251 Integer.toString(remainingAttempts));
252 status.setText(warning);
253 } else {
254 int passwordType = StorageManager.CRYPT_TYPE_PASSWORD;
255 try {
256 final IMountService service = getMountService();
257 passwordType = service.getPasswordType();
258 } catch (Exception e) {
259 Log.e(TAG, "Error calling mount service " + e);
Paul Lawrencef6cda3b2014-06-12 08:26:08 -0700260 }
Paul Crowley2555e5f2014-11-07 00:52:57 -0800261
262 if (passwordType == StorageManager.CRYPT_TYPE_PIN) {
263 status.setText(R.string.cryptkeeper_wrong_pin);
264 } else if (passwordType == StorageManager.CRYPT_TYPE_PATTERN) {
265 status.setText(R.string.cryptkeeper_wrong_pattern);
Paul Lawrencef6cda3b2014-06-12 08:26:08 -0700266 } else {
Paul Crowley2555e5f2014-11-07 00:52:57 -0800267 status.setText(R.string.cryptkeeper_wrong_password);
Paul Lawrence2daf2642014-03-14 09:20:24 -0700268 }
Jason parks06c5ff42011-03-01 10:17:40 -0600269 }
Paul Crowley2555e5f2014-11-07 00:52:57 -0800270
271 if (mLockPatternView != null) {
272 mLockPatternView.setDisplayMode(DisplayMode.Wrong);
273 mLockPatternView.setEnabled(true);
274 }
275
276 // Reenable the password entry
277 if (mPasswordEntry != null) {
278 mPasswordEntry.setEnabled(true);
279 final InputMethodManager imm = (InputMethodManager) getSystemService(
280 Context.INPUT_METHOD_SERVICE);
281 imm.showSoftInput(mPasswordEntry, 0);
282 setBackFunctionality(true);
283 }
Jason parks06c5ff42011-03-01 10:17:40 -0600284 }
285 }
Jason parks75c085e2011-02-10 14:03:47 -0600286
Ben Komalo0e666092011-09-01 15:42:00 -0700287 private class ValidationTask extends AsyncTask<Void, Void, Boolean> {
Paul Lawrence87abbd32014-08-28 15:56:38 -0700288 int state;
289
Ben Komalo0e666092011-09-01 15:42:00 -0700290 @Override
291 protected Boolean doInBackground(Void... params) {
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700292 final IMountService service = getMountService();
Ben Komalo0e666092011-09-01 15:42:00 -0700293 try {
Ben Komalod4758ef2011-09-08 14:36:08 -0700294 Log.d(TAG, "Validating encryption state.");
Paul Lawrence87abbd32014-08-28 15:56:38 -0700295 state = service.getEncryptionState();
Ben Komalo0e666092011-09-01 15:42:00 -0700296 if (state == IMountService.ENCRYPTION_STATE_NONE) {
297 Log.w(TAG, "Unexpectedly in CryptKeeper even though there is no encryption.");
298 return true; // Unexpected, but fine, I guess...
299 }
300 return state == IMountService.ENCRYPTION_STATE_OK;
301 } catch (RemoteException e) {
302 Log.w(TAG, "Unable to get encryption state properly");
303 return true;
304 }
305 }
306
307 @Override
308 protected void onPostExecute(Boolean result) {
309 mValidationComplete = true;
310 if (Boolean.FALSE.equals(result)) {
311 Log.w(TAG, "Incomplete, or corrupted encryption detected. Prompting user to wipe.");
312 mEncryptionGoneBad = true;
Paul Lawrence87abbd32014-08-28 15:56:38 -0700313 mCorrupt = state == IMountService.ENCRYPTION_STATE_ERROR_CORRUPT;
Ben Komalod4758ef2011-09-08 14:36:08 -0700314 } else {
315 Log.d(TAG, "Encryption state validated. Proceeding to configure UI");
Ben Komalo0e666092011-09-01 15:42:00 -0700316 }
317 setupUi();
318 }
319 }
320
Ben Komalo91a2f052011-08-16 17:48:25 -0700321 private final Handler mHandler = new Handler() {
Jason parksec5a45e2011-01-18 15:28:36 -0600322 @Override
323 public void handleMessage(Message msg) {
Jason parksec5a45e2011-01-18 15:28:36 -0600324 switch (msg.what) {
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700325 case MESSAGE_UPDATE_PROGRESS:
Jason parksf8217302011-01-26 13:11:42 -0600326 updateProgress();
Jason parksec5a45e2011-01-18 15:28:36 -0600327 break;
Jason parks35933812011-01-21 15:48:20 -0600328
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700329 case MESSAGE_NOTIFY:
330 notifyUser();
331 break;
Jason parksec5a45e2011-01-18 15:28:36 -0600332 }
333 }
334 };
Jason parks35933812011-01-21 15:48:20 -0600335
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700336 private AudioManager mAudioManager;
Vikram Aggarwalbf459da2012-11-08 16:54:59 -0800337 /** The status bar where back/home/recent buttons are shown. */
338 private StatusBarManager mStatusBar;
339
340 /** All the widgets to disable in the status bar */
341 final private static int sWidgetsToDisable = StatusBarManager.DISABLE_EXPAND
342 | StatusBarManager.DISABLE_NOTIFICATION_ICONS
343 | StatusBarManager.DISABLE_NOTIFICATION_ALERTS
344 | StatusBarManager.DISABLE_SYSTEM_INFO
345 | StatusBarManager.DISABLE_HOME
Alon Albert66d050b2013-09-30 17:08:12 -0700346 | StatusBarManager.DISABLE_SEARCH
Vikram Aggarwalbf459da2012-11-08 16:54:59 -0800347 | StatusBarManager.DISABLE_RECENT;
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700348
Paul Crowley2555e5f2014-11-07 00:52:57 -0800349 protected static final int MIN_LENGTH_BEFORE_REPORT = LockPatternUtils.MIN_LOCK_PATTERN_SIZE;
350
Ben Komalo91a2f052011-08-16 17:48:25 -0700351 /** @return whether or not this Activity was started for debugging the UI only. */
352 private boolean isDebugView() {
353 return getIntent().hasExtra(EXTRA_FORCE_VIEW);
354 }
355
356 /** @return whether or not this Activity was started for debugging the specific UI view only. */
357 private boolean isDebugView(String viewType /* non-nullable */) {
358 return viewType.equals(getIntent().getStringExtra(EXTRA_FORCE_VIEW));
359 }
360
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700361 /**
362 * Notify the user that we are awaiting input. Currently this sends an audio alert.
363 */
364 private void notifyUser() {
Vikram Aggarwald1147252012-05-08 13:52:30 -0700365 if (mNotificationCountdown > 0) {
Vikram Aggarwald1147252012-05-08 13:52:30 -0700366 --mNotificationCountdown;
367 } else if (mAudioManager != null) {
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700368 try {
369 // Play the standard keypress sound at full volume. This should be available on
370 // every device. We cannot play a ringtone here because media services aren't
371 // available yet. A DTMF-style tone is too soft to be noticed, and might not exist
372 // on tablet devices. The idea is to alert the user that something is needed: this
373 // does not have to be pleasing.
374 mAudioManager.playSoundEffect(AudioManager.FX_KEYPRESS_STANDARD, 100);
375 } catch (Exception e) {
376 Log.w(TAG, "notifyUser: Exception while playing sound: " + e);
377 }
378 }
Vikram Aggarwal86b93932012-05-01 16:46:06 -0700379 // Notify the user again in 5 seconds.
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700380 mHandler.removeMessages(MESSAGE_NOTIFY);
Vikram Aggarwal86b93932012-05-01 16:46:06 -0700381 mHandler.sendEmptyMessageDelayed(MESSAGE_NOTIFY, 5 * 1000);
Paul Lawrence73456ac2014-05-16 07:56:04 -0700382
383 if (mWakeLock.isHeld()) {
384 if (mReleaseWakeLockCountdown > 0) {
385 --mReleaseWakeLockCountdown;
386 } else {
387 mWakeLock.release();
388 }
389 }
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700390 }
391
392 /**
393 * Ignore back events after the user has entered the decrypt screen and while the device is
394 * encrypting.
395 */
396 @Override
397 public void onBackPressed() {
Vikram Aggarwalbf459da2012-11-08 16:54:59 -0800398 // In the rare case that something pressed back even though we were disabled.
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700399 if (mIgnoreBack)
400 return;
401 super.onBackPressed();
402 }
403
Jason parks8fd5bc92011-01-12 16:03:31 -0600404 @Override
405 public void onCreate(Bundle savedInstanceState) {
406 super.onCreate(savedInstanceState);
Jason parks35933812011-01-21 15:48:20 -0600407
Andy Stadler95974062011-02-01 17:35:20 -0800408 // If we are not encrypted or encrypting, get out quickly.
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700409 final String state = SystemProperties.get("vold.decrypt");
Ben Komalo91a2f052011-08-16 17:48:25 -0700410 if (!isDebugView() && ("".equals(state) || DECRYPT_STATE.equals(state))) {
Jason parks35933812011-01-21 15:48:20 -0600411 // Disable the crypt keeper.
Jason parks8fd5bc92011-01-12 16:03:31 -0600412 PackageManager pm = getPackageManager();
413 ComponentName name = new ComponentName(this, CryptKeeper.class);
Dianne Hackborn140f6c62011-10-16 11:49:00 -0700414 pm.setComponentEnabledSetting(name, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
415 PackageManager.DONT_KILL_APP);
416 // Typically CryptKeeper is launched as the home app. We didn't
Dianne Hackborn644fa422011-10-18 13:38:03 -0700417 // want to be running, so need to finish this activity. We can count
418 // on the activity manager re-launching the new home app upon finishing
419 // this one, since this will leave the activity stack empty.
Dianne Hackborn140f6c62011-10-16 11:49:00 -0700420 // NOTE: This is really grungy. I think it would be better for the
421 // activity manager to explicitly launch the crypt keeper instead of
422 // home in the situation where we need to decrypt the device
423 finish();
Jason parks8fd5bc92011-01-12 16:03:31 -0600424 return;
425 }
Jason parks35933812011-01-21 15:48:20 -0600426
Paul Lawrence7ae20e32014-07-22 15:00:50 -0700427 try {
428 if (getResources().getBoolean(R.bool.crypt_keeper_allow_rotation)) {
429 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
430 }
431 } catch (NotFoundException e) {
432 }
433
Vikram Aggarwalb96b35a2012-05-01 11:09:39 -0700434 // Disable the status bar, but do NOT disable back because the user needs a way to go
435 // from keyboard settings and back to the password screen.
Vikram Aggarwalbf459da2012-11-08 16:54:59 -0800436 mStatusBar = (StatusBarManager) getSystemService(Context.STATUS_BAR_SERVICE);
437 mStatusBar.disable(sWidgetsToDisable);
Andy Stadler14997402011-02-01 15:34:59 -0800438
Vikram Aggarwalea1186d2012-05-03 15:35:03 -0700439 setAirplaneModeIfNecessary();
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700440 mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
Andy Stadler14997402011-02-01 15:34:59 -0800441 // Check for (and recover) retained instance data
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700442 final Object lastInstance = getLastNonConfigurationInstance();
Andy Stadler14997402011-02-01 15:34:59 -0800443 if (lastInstance instanceof NonConfigurationInstanceState) {
444 NonConfigurationInstanceState retained = (NonConfigurationInstanceState) lastInstance;
445 mWakeLock = retained.wakelock;
Ben Komalo04606752011-08-18 14:50:26 -0700446 Log.d(TAG, "Restoring wakelock from NonConfigurationInstanceState");
Andy Stadler14997402011-02-01 15:34:59 -0800447 }
Jason parksec5a45e2011-01-18 15:28:36 -0600448 }
Jason parks35933812011-01-21 15:48:20 -0600449
Andy Stadler95974062011-02-01 17:35:20 -0800450 /**
451 * Note, we defer the state check and screen setup to onStart() because this will be
452 * re-run if the user clicks the power button (sleeping/waking the screen), and this is
453 * especially important if we were to lose the wakelock for any reason.
454 */
455 @Override
456 public void onStart() {
457 super.onStart();
Ben Komalod4758ef2011-09-08 14:36:08 -0700458 setupUi();
Ben Komalo0e666092011-09-01 15:42:00 -0700459 }
460
461 /**
462 * Initializes the UI based on the current state of encryption.
463 * This is idempotent - calling repeatedly will simply re-initialize the UI.
464 */
465 private void setupUi() {
466 if (mEncryptionGoneBad || isDebugView(FORCE_VIEW_ERROR)) {
467 setContentView(R.layout.crypt_keeper_progress);
Paul Lawrence87abbd32014-08-28 15:56:38 -0700468 showFactoryReset(mCorrupt);
Ben Komalo0e666092011-09-01 15:42:00 -0700469 return;
470 }
471
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700472 final String progress = SystemProperties.get("vold.encrypt_progress");
Ben Komalo0e666092011-09-01 15:42:00 -0700473 if (!"".equals(progress) || isDebugView(FORCE_VIEW_PROGRESS)) {
Andy Stadler95974062011-02-01 17:35:20 -0800474 setContentView(R.layout.crypt_keeper_progress);
475 encryptionProgressInit();
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700476 } else if (mValidationComplete || isDebugView(FORCE_VIEW_PASSWORD)) {
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700477 new AsyncTask<Void, Void, Void>() {
Paul Crowley529834d2014-10-21 10:12:47 +0100478 int passwordType = StorageManager.CRYPT_TYPE_PASSWORD;
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700479 String owner_info;
Paul Lawrence0f11e152014-08-20 07:43:32 -0700480 boolean pattern_visible;
Paul Lawrenceb05f39d2014-02-04 10:22:19 -0800481
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700482 @Override
483 public Void doInBackground(Void... v) {
484 try {
485 final IMountService service = getMountService();
Paul Crowley529834d2014-10-21 10:12:47 +0100486 passwordType = service.getPasswordType();
Elliott Hughesf9d6d292014-10-02 13:29:58 -0700487 owner_info = service.getField(StorageManager.OWNER_INFO_KEY);
488 pattern_visible = !("0".equals(service.getField(StorageManager.PATTERN_VISIBLE_KEY)));
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700489 } catch (Exception e) {
490 Log.e(TAG, "Error calling mount service " + e);
491 }
492
493 return null;
494 }
495
496 @Override
497 public void onPostExecute(java.lang.Void v) {
Paul Crowley51e08112014-11-12 12:06:38 +0000498 if (passwordType == StorageManager.CRYPT_TYPE_PIN) {
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700499 setContentView(R.layout.crypt_keeper_pin_entry);
Paul Lawrence5a70f052014-06-13 11:09:55 -0700500 mStatusString = R.string.enter_pin;
Paul Crowley529834d2014-10-21 10:12:47 +0100501 } else if (passwordType == StorageManager.CRYPT_TYPE_PATTERN) {
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700502 setContentView(R.layout.crypt_keeper_pattern_entry);
503 setBackFunctionality(false);
Paul Lawrence5a70f052014-06-13 11:09:55 -0700504 mStatusString = R.string.enter_pattern;
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700505 } else {
506 setContentView(R.layout.crypt_keeper_password_entry);
Paul Lawrence5a70f052014-06-13 11:09:55 -0700507 mStatusString = R.string.enter_password;
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700508 }
Paul Lawrence5a70f052014-06-13 11:09:55 -0700509 final TextView status = (TextView) findViewById(R.id.status);
510 status.setText(mStatusString);
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700511
Paul Lawrence5a70f052014-06-13 11:09:55 -0700512 final TextView ownerInfo = (TextView) findViewById(R.id.owner_info);
513 ownerInfo.setText(owner_info);
514 ownerInfo.setSelected(true); // Required for marquee'ing to work
515
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700516 passwordEntryInit();
Paul Lawrence5a70f052014-06-13 11:09:55 -0700517
Paul Lawrence0f11e152014-08-20 07:43:32 -0700518 if (mLockPatternView != null) {
519 mLockPatternView.setInStealthMode(!pattern_visible);
520 }
Paul Crowley51e08112014-11-12 12:06:38 +0000521 if (mCooldown) {
522 // in case we are cooling down and coming back from emergency dialler
Paul Lawrence5a70f052014-06-13 11:09:55 -0700523 setBackFunctionality(false);
Paul Crowley51e08112014-11-12 12:06:38 +0000524 cooldown();
Paul Lawrence5a70f052014-06-13 11:09:55 -0700525 }
Paul Crowley51e08112014-11-12 12:06:38 +0000526
Paul Lawrence9ac2d812014-03-18 10:59:18 -0700527 }
528 }.execute();
Ben Komalod4758ef2011-09-08 14:36:08 -0700529 } else if (!mValidationRequested) {
530 // We're supposed to be encrypted, but no validation has been done.
531 new ValidationTask().execute((Void[]) null);
532 mValidationRequested = true;
Andy Stadler95974062011-02-01 17:35:20 -0800533 }
534 }
535
Jason parksf8217302011-01-26 13:11:42 -0600536 @Override
537 public void onStop() {
538 super.onStop();
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700539 mHandler.removeMessages(MESSAGE_UPDATE_PROGRESS);
540 mHandler.removeMessages(MESSAGE_NOTIFY);
Andy Stadler14997402011-02-01 15:34:59 -0800541 }
542
543 /**
544 * Reconfiguring, so propagate the wakelock to the next instance. This runs between onStop()
545 * and onDestroy() and only if we are changing configuration (e.g. rotation). Also clears
546 * mWakeLock so the subsequent call to onDestroy does not release it.
547 */
548 @Override
549 public Object onRetainNonConfigurationInstance() {
550 NonConfigurationInstanceState state = new NonConfigurationInstanceState(mWakeLock);
Ben Komalo04606752011-08-18 14:50:26 -0700551 Log.d(TAG, "Handing wakelock off to NonConfigurationInstanceState");
Andy Stadler14997402011-02-01 15:34:59 -0800552 mWakeLock = null;
553 return state;
554 }
555
556 @Override
557 public void onDestroy() {
558 super.onDestroy();
Jason parksf8217302011-01-26 13:11:42 -0600559
560 if (mWakeLock != null) {
Ben Komalo04606752011-08-18 14:50:26 -0700561 Log.d(TAG, "Releasing and destroying wakelock");
Jason parksf8217302011-01-26 13:11:42 -0600562 mWakeLock.release();
563 mWakeLock = null;
564 }
565 }
566
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700567 /**
568 * Start encrypting the device.
569 */
Jason parksec5a45e2011-01-18 15:28:36 -0600570 private void encryptionProgressInit() {
Jason parks35933812011-01-21 15:48:20 -0600571 // Accquire a partial wakelock to prevent the device from sleeping. Note
572 // we never release this wakelock as we will be restarted after the device
573 // is encrypted.
Ben Komalo04606752011-08-18 14:50:26 -0700574 Log.d(TAG, "Encryption progress screen initializing.");
Ben Komalo9ee164f2011-09-21 10:40:50 -0700575 if (mWakeLock == null) {
Ben Komalo04606752011-08-18 14:50:26 -0700576 Log.d(TAG, "Acquiring wakelock.");
577 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
578 mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);
579 mWakeLock.acquire();
580 }
Jason parks35933812011-01-21 15:48:20 -0600581
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700582 ((ProgressBar) findViewById(R.id.progress_bar)).setIndeterminate(true);
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700583 // Ignore all back presses from now, both hard and soft keys.
Vikram Aggarwalbf459da2012-11-08 16:54:59 -0800584 setBackFunctionality(false);
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700585 // Start the first run of progress manually. This method sets up messages to occur at
586 // repeated intervals.
Jason parksf8217302011-01-26 13:11:42 -0600587 updateProgress();
588 }
589
Paul Lawrence384d8e52014-08-08 15:11:36 -0700590 /**
591 * Show factory reset screen allowing the user to reset their phone when
592 * there is nothing else we can do
593 * @param corrupt true if userdata is corrupt, false if encryption failed
594 * partway through
595 */
Jeff Sharkey1de688d2014-09-24 13:57:07 -0700596 private void showFactoryReset(final boolean corrupt) {
Andy Stadler13d62042011-01-31 19:21:37 -0800597 // Hide the encryption-bot to make room for the "factory reset" button
598 findViewById(R.id.encroid).setVisibility(View.GONE);
599
600 // Show the reset button, failure text, and a divider
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700601 final Button button = (Button) findViewById(R.id.factory_reset);
Andy Stadler13d62042011-01-31 19:21:37 -0800602 button.setVisibility(View.VISIBLE);
603 button.setOnClickListener(new OnClickListener() {
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700604 @Override
Andy Stadler13d62042011-01-31 19:21:37 -0800605 public void onClick(View v) {
606 // Factory reset the device.
Jeff Sharkey1de688d2014-09-24 13:57:07 -0700607 Intent intent = new Intent(Intent.ACTION_MASTER_CLEAR);
608 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
609 intent.putExtra(Intent.EXTRA_REASON,
610 "CryptKeeper.showFactoryReset() corrupt=" + corrupt);
611 sendBroadcast(intent);
Andy Stadler13d62042011-01-31 19:21:37 -0800612 }
613 });
614
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700615 // Alert the user of the failure.
Paul Lawrence384d8e52014-08-08 15:11:36 -0700616 if (corrupt) {
617 ((TextView) findViewById(R.id.title)).setText(R.string.crypt_keeper_data_corrupt_title);
618 ((TextView) findViewById(R.id.status)).setText(R.string.crypt_keeper_data_corrupt_summary);
619 } else {
620 ((TextView) findViewById(R.id.title)).setText(R.string.crypt_keeper_failed_title);
621 ((TextView) findViewById(R.id.status)).setText(R.string.crypt_keeper_failed_summary);
622 }
Andy Stadler13d62042011-01-31 19:21:37 -0800623
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700624 final View view = findViewById(R.id.bottom_divider);
625 // TODO(viki): Why would the bottom divider be missing in certain layouts? Investigate.
Ben Komalof0104df2011-08-16 17:48:42 -0700626 if (view != null) {
627 view.setVisibility(View.VISIBLE);
628 }
Andy Stadler13d62042011-01-31 19:21:37 -0800629 }
630
Jason parksf8217302011-01-26 13:11:42 -0600631 private void updateProgress() {
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700632 final String state = SystemProperties.get("vold.encrypt_progress");
Jason parksf8217302011-01-26 13:11:42 -0600633
Ben Komalo0e666092011-09-01 15:42:00 -0700634 if ("error_partially_encrypted".equals(state)) {
Paul Lawrence384d8e52014-08-08 15:11:36 -0700635 showFactoryReset(false);
Andy Stadler13d62042011-01-31 19:21:37 -0800636 return;
637 }
638
Paul Lawrenceb15c68f2014-06-05 07:24:23 -0700639 // Get status as percentage first
640 CharSequence status = getText(R.string.crypt_keeper_setup_description);
641 int percent = 0;
Jason parksf8217302011-01-26 13:11:42 -0600642 try {
Ben Komalo91a2f052011-08-16 17:48:25 -0700643 // Force a 50% progress state when debugging the view.
Paul Lawrenceb15c68f2014-06-05 07:24:23 -0700644 percent = isDebugView() ? 50 : Integer.parseInt(state);
Jason parksf8217302011-01-26 13:11:42 -0600645 } catch (Exception e) {
646 Log.w(TAG, "Error parsing progress: " + e.toString());
647 }
Paul Lawrenceb15c68f2014-06-05 07:24:23 -0700648 String progress = Integer.toString(percent);
Jason parksf8217302011-01-26 13:11:42 -0600649
Paul Lawrenceb15c68f2014-06-05 07:24:23 -0700650 // Now try to get status as time remaining and replace as appropriate
Ben Komalo04606752011-08-18 14:50:26 -0700651 Log.v(TAG, "Encryption progress: " + progress);
Paul Lawrenceb15c68f2014-06-05 07:24:23 -0700652 try {
653 final String timeProperty = SystemProperties.get("vold.encrypt_time_remaining");
654 int time = Integer.parseInt(timeProperty);
655 if (time >= 0) {
656 // Round up to multiple of 10 - this way display is less jerky
657 time = (time + 9) / 10 * 10;
658 progress = DateUtils.formatElapsedTime(time);
659 status = getText(R.string.crypt_keeper_setup_time_remaining);
660 }
661 } catch (Exception e) {
662 // Will happen if no time etc - show percentage
663 }
664
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700665 final TextView tv = (TextView) findViewById(R.id.status);
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700666 if (tv != null) {
Paul Lawrenceb15c68f2014-06-05 07:24:23 -0700667 tv.setText(TextUtils.expandTemplate(status, progress));
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700668 }
Paul Lawrenceb15c68f2014-06-05 07:24:23 -0700669
670 // Check the progress every 1 seconds
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700671 mHandler.removeMessages(MESSAGE_UPDATE_PROGRESS);
Paul Lawrenceb15c68f2014-06-05 07:24:23 -0700672 mHandler.sendEmptyMessageDelayed(MESSAGE_UPDATE_PROGRESS, 1000);
Jason parksf8217302011-01-26 13:11:42 -0600673 }
674
Paul Crowley51e08112014-11-12 12:06:38 +0000675 /** Insist on a power cycle to force the user to waste time between retries.
676 *
677 * Call setBackFunctionality(false) before calling this. */
Jason parksf8217302011-01-26 13:11:42 -0600678 private void cooldown() {
Paul Crowley51e08112014-11-12 12:06:38 +0000679 // Disable the password entry.
680 if (mPasswordEntry != null) {
681 mPasswordEntry.setEnabled(false);
Jason parksf8217302011-01-26 13:11:42 -0600682 }
Paul Crowley51e08112014-11-12 12:06:38 +0000683 if (mLockPatternView != null) {
684 mLockPatternView.setEnabled(false);
685 }
686
687 final TextView status = (TextView) findViewById(R.id.status);
688 status.setText(R.string.crypt_keeper_force_power_cycle);
Jason parksec5a45e2011-01-18 15:28:36 -0600689 }
Jason parks35933812011-01-21 15:48:20 -0600690
Vikram Aggarwalbf459da2012-11-08 16:54:59 -0800691 /**
692 * Sets the back status: enabled or disabled according to the parameter.
693 * @param isEnabled true if back is enabled, false otherwise.
694 */
695 private final void setBackFunctionality(boolean isEnabled) {
696 mIgnoreBack = !isEnabled;
697 if (isEnabled) {
698 mStatusBar.disable(sWidgetsToDisable);
699 } else {
700 mStatusBar.disable(sWidgetsToDisable | StatusBarManager.DISABLE_BACK);
701 }
702 }
703
Paul Crowley2555e5f2014-11-07 00:52:57 -0800704 private void fakeUnlockAttempt(View postingView) {
705 beginAttempt();
706 postingView.postDelayed(mFakeUnlockAttemptRunnable, FAKE_ATTEMPT_DELAY);
707 }
708
Paul Lawrenceb05f39d2014-02-04 10:22:19 -0800709 protected LockPatternView.OnPatternListener mChooseNewLockPatternListener =
Paul Lawrencef6cda3b2014-06-12 08:26:08 -0700710 new LockPatternView.OnPatternListener() {
Paul Lawrenceb05f39d2014-02-04 10:22:19 -0800711
Paul Lawrencef6cda3b2014-06-12 08:26:08 -0700712 @Override
713 public void onPatternStart() {
714 mLockPatternView.removeCallbacks(mClearPatternRunnable);
715 }
Paul Lawrenceb05f39d2014-02-04 10:22:19 -0800716
Paul Lawrencef6cda3b2014-06-12 08:26:08 -0700717 @Override
718 public void onPatternCleared() {
719 }
Paul Lawrenceb05f39d2014-02-04 10:22:19 -0800720
Paul Lawrencef6cda3b2014-06-12 08:26:08 -0700721 @Override
722 public void onPatternDetected(List<LockPatternView.Cell> pattern) {
723 mLockPatternView.setEnabled(false);
Paul Crowley2555e5f2014-11-07 00:52:57 -0800724 if (pattern.size() >= MIN_LENGTH_BEFORE_REPORT) {
725 new DecryptTask().execute(LockPatternUtils.patternToString(pattern));
726 } else {
727 // Allow user to make as many of these as they want.
728 fakeUnlockAttempt(mLockPatternView);
729 }
Paul Lawrencef6cda3b2014-06-12 08:26:08 -0700730 }
Paul Lawrenceb05f39d2014-02-04 10:22:19 -0800731
Paul Lawrencef6cda3b2014-06-12 08:26:08 -0700732 @Override
733 public void onPatternCellAdded(List<Cell> pattern) {
734 }
Paul Lawrenceb05f39d2014-02-04 10:22:19 -0800735 };
736
737 private void passwordEntryInit() {
738 // Password/pin case
Jason parks06c5ff42011-03-01 10:17:40 -0600739 mPasswordEntry = (EditText) findViewById(R.id.passwordEntry);
Paul Lawrenceb05f39d2014-02-04 10:22:19 -0800740 if (mPasswordEntry != null){
741 mPasswordEntry.setOnEditorActionListener(this);
742 mPasswordEntry.requestFocus();
743 // Become quiet when the user interacts with the Edit text screen.
744 mPasswordEntry.setOnKeyListener(this);
745 mPasswordEntry.setOnTouchListener(this);
746 mPasswordEntry.addTextChangedListener(this);
747 }
748
749 // Pattern case
750 mLockPatternView = (LockPatternView) findViewById(R.id.lockPattern);
751 if (mLockPatternView != null) {
752 mLockPatternView.setOnPatternListener(mChooseNewLockPatternListener);
753 }
Jason parks35933812011-01-21 15:48:20 -0600754
Vikram Aggarwalc62d3212012-05-02 16:29:10 -0700755 // Disable the Emergency call button if the device has no voice telephone capability
Santos Cordon3afbdf02014-05-29 21:48:16 -0700756 if (!getTelephonyManager().isVoiceCapable()) {
Vikram Aggarwalc62d3212012-05-02 16:29:10 -0700757 final View emergencyCall = findViewById(R.id.emergencyCallButton);
758 if (emergencyCall != null) {
759 Log.d(TAG, "Removing the emergency Call button");
760 emergencyCall.setVisibility(View.GONE);
761 }
762 }
763
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700764 final View imeSwitcher = findViewById(R.id.switch_ime_button);
Ben Komalo9fcb6a72011-08-26 14:40:18 -0700765 final InputMethodManager imm = (InputMethodManager) getSystemService(
766 Context.INPUT_METHOD_SERVICE);
767 if (imeSwitcher != null && hasMultipleEnabledIMEsOrSubtypes(imm, false)) {
768 imeSwitcher.setVisibility(View.VISIBLE);
769 imeSwitcher.setOnClickListener(new OnClickListener() {
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700770 @Override
Ben Komalo9fcb6a72011-08-26 14:40:18 -0700771 public void onClick(View v) {
772 imm.showInputMethodPicker();
773 }
774 });
Jason parks00046d62011-06-13 17:38:45 -0500775 }
David Brown8373b452011-06-20 12:38:45 -0700776
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700777 // We want to keep the screen on while waiting for input. In minimal boot mode, the device
778 // is completely non-functional, and we want the user to notice the device and enter a
779 // password.
780 if (mWakeLock == null) {
781 Log.d(TAG, "Acquiring wakelock.");
782 final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
783 if (pm != null) {
784 mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);
785 mWakeLock.acquire();
Paul Lawrence73456ac2014-05-16 07:56:04 -0700786 // Keep awake for 10 minutes - if the user hasn't been alerted by then
787 // best not to just drain their battery
Paul Lawrence5a70f052014-06-13 11:09:55 -0700788 mReleaseWakeLockCountdown = 96; // 96 * 5 secs per click + 120 secs before we show this = 600
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700789 }
790 }
Paul Lawrence73456ac2014-05-16 07:56:04 -0700791
Ben Komalo9fcb6a72011-08-26 14:40:18 -0700792 // Asynchronously throw up the IME, since there are issues with requesting it to be shown
793 // immediately.
Paul Crowley51e08112014-11-12 12:06:38 +0000794 if (mLockPatternView == null && !mCooldown) {
Paul Lawrencee54e9322014-03-13 14:05:48 -0700795 mHandler.postDelayed(new Runnable() {
796 @Override public void run() {
797 imm.showSoftInputUnchecked(0, null);
798 }
799 }, 0);
800 }
Ben Komalo9fcb6a72011-08-26 14:40:18 -0700801
David Brown8373b452011-06-20 12:38:45 -0700802 updateEmergencyCallButtonState();
Vikram Aggarwald1147252012-05-08 13:52:30 -0700803 // Notify the user in 120 seconds that we are waiting for him to enter the password.
Vikram Aggarwal86b93932012-05-01 16:46:06 -0700804 mHandler.removeMessages(MESSAGE_NOTIFY);
Vikram Aggarwald1147252012-05-08 13:52:30 -0700805 mHandler.sendEmptyMessageDelayed(MESSAGE_NOTIFY, 120 * 1000);
Jim Millerfb3d5ca2013-11-14 14:40:22 -0800806
John Spurlock2c526512014-09-17 12:55:17 -0400807 // Dismiss secure & non-secure keyguards while this screen is showing.
808 getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
809 | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
Jason parks8fd5bc92011-01-12 16:03:31 -0600810 }
811
Ben Komalo9fcb6a72011-08-26 14:40:18 -0700812 /**
813 * Method adapted from com.android.inputmethod.latin.Utils
814 *
815 * @param imm The input method manager
816 * @param shouldIncludeAuxiliarySubtypes
817 * @return true if we have multiple IMEs to choose from
818 */
819 private boolean hasMultipleEnabledIMEsOrSubtypes(InputMethodManager imm,
820 final boolean shouldIncludeAuxiliarySubtypes) {
821 final List<InputMethodInfo> enabledImis = imm.getEnabledInputMethodList();
822
823 // Number of the filtered IMEs
824 int filteredImisCount = 0;
825
826 for (InputMethodInfo imi : enabledImis) {
827 // We can return true immediately after we find two or more filtered IMEs.
828 if (filteredImisCount > 1) return true;
829 final List<InputMethodSubtype> subtypes =
830 imm.getEnabledInputMethodSubtypeList(imi, true);
831 // IMEs that have no subtypes should be counted.
832 if (subtypes.isEmpty()) {
833 ++filteredImisCount;
834 continue;
835 }
836
837 int auxCount = 0;
838 for (InputMethodSubtype subtype : subtypes) {
839 if (subtype.isAuxiliary()) {
840 ++auxCount;
841 }
842 }
843 final int nonAuxCount = subtypes.size() - auxCount;
844
845 // IMEs that have one or more non-auxiliary subtypes should be counted.
846 // If shouldIncludeAuxiliarySubtypes is true, IMEs that have two or more auxiliary
847 // subtypes should be counted as well.
848 if (nonAuxCount > 0 || (shouldIncludeAuxiliarySubtypes && auxCount > 1)) {
849 ++filteredImisCount;
850 continue;
851 }
852 }
853
854 return filteredImisCount > 1
855 // imm.getEnabledInputMethodSubtypeList(null, false) will return the current IME's enabled
856 // input method subtype (The current IME should be LatinIME.)
857 || imm.getEnabledInputMethodSubtypeList(null, false).size() > 1;
858 }
859
Jason parks8fd5bc92011-01-12 16:03:31 -0600860 private IMountService getMountService() {
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700861 final IBinder service = ServiceManager.getService("mount");
Jason parks8fd5bc92011-01-12 16:03:31 -0600862 if (service != null) {
863 return IMountService.Stub.asInterface(service);
864 }
865 return null;
866 }
867
868 @Override
869 public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
Jason parks00046d62011-06-13 17:38:45 -0500870 if (actionId == EditorInfo.IME_NULL || actionId == EditorInfo.IME_ACTION_DONE) {
Jason parks8fd5bc92011-01-12 16:03:31 -0600871 // Get the password
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700872 final String password = v.getText().toString();
Jason parks8fd5bc92011-01-12 16:03:31 -0600873
Jason parksec5a45e2011-01-18 15:28:36 -0600874 if (TextUtils.isEmpty(password)) {
875 return true;
876 }
Jason parks35933812011-01-21 15:48:20 -0600877
Jason parks8fd5bc92011-01-12 16:03:31 -0600878 // Now that we have the password clear the password field.
879 v.setText(null);
880
Vikram Aggarwalde3c9cb2012-05-01 15:37:30 -0700881 // Disable the password entry and back keypress while checking the password. These
882 // we either be re-enabled if the password was wrong or after the cooldown period.
Jason parks06c5ff42011-03-01 10:17:40 -0600883 mPasswordEntry.setEnabled(false);
Vikram Aggarwalbf459da2012-11-08 16:54:59 -0800884 setBackFunctionality(false);
Jason parks8fd5bc92011-01-12 16:03:31 -0600885
Paul Crowley2555e5f2014-11-07 00:52:57 -0800886 if (password.length() >= LockPatternUtils.MIN_LOCK_PATTERN_SIZE) {
887 new DecryptTask().execute(password);
888 } else {
889 // Allow user to make as many of these as they want.
890 fakeUnlockAttempt(mPasswordEntry);
891 }
Jason parks35933812011-01-21 15:48:20 -0600892
Jason parks8fd5bc92011-01-12 16:03:31 -0600893 return true;
894 }
895 return false;
896 }
David Brown8373b452011-06-20 12:38:45 -0700897
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700898 /**
Vikram Aggarwalea1186d2012-05-03 15:35:03 -0700899 * Set airplane mode on the device if it isn't an LTE device.
900 * Full story: In minimal boot mode, we cannot save any state. In particular, we cannot save
901 * any incoming SMS's. So SMSs that are received here will be silently dropped to the floor.
902 * That is bad. Also, we cannot receive any telephone calls in this state. So to avoid
903 * both these problems, we turn the radio off. However, on certain networks turning on and
904 * off the radio takes a long time. In such cases, we are better off leaving the radio
905 * running so the latency of an E911 call is short.
906 * The behavior after this is:
907 * 1. Emergency dialing: the emergency dialer has logic to force the device out of
908 * airplane mode and restart the radio.
909 * 2. Full boot: we read the persistent settings from the previous boot and restore the
910 * radio to whatever it was before it restarted. This also happens when rebooting a
911 * phone that has no encryption.
912 */
913 private final void setAirplaneModeIfNecessary() {
914 final boolean isLteDevice =
Santos Cordon3afbdf02014-05-29 21:48:16 -0700915 getTelephonyManager().getLteOnCdmaMode() == PhoneConstants.LTE_ON_CDMA_TRUE;
Vikram Aggarwalea1186d2012-05-03 15:35:03 -0700916 if (!isLteDevice) {
917 Log.d(TAG, "Going into airplane mode.");
Christopher Tate6a5929b2012-09-10 15:39:05 -0700918 Settings.Global.putInt(getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 1);
Vikram Aggarwalea1186d2012-05-03 15:35:03 -0700919 final Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
920 intent.putExtra("state", true);
Christopher Tate6a5929b2012-09-10 15:39:05 -0700921 sendBroadcastAsUser(intent, UserHandle.ALL);
Vikram Aggarwalea1186d2012-05-03 15:35:03 -0700922 }
923 }
924
925 /**
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700926 * Code to update the state of, and handle clicks from, the "Emergency call" button.
927 *
928 * This code is mostly duplicated from the corresponding code in
929 * LockPatternUtils and LockPatternKeyguardView under frameworks/base.
930 */
David Brown8373b452011-06-20 12:38:45 -0700931 private void updateEmergencyCallButtonState() {
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700932 final Button emergencyCall = (Button) findViewById(R.id.emergencyCallButton);
David Brown8373b452011-06-20 12:38:45 -0700933 // The button isn't present at all in some configurations.
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700934 if (emergencyCall == null)
935 return;
David Brown8373b452011-06-20 12:38:45 -0700936
937 if (isEmergencyCallCapable()) {
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700938 emergencyCall.setVisibility(View.VISIBLE);
939 emergencyCall.setOnClickListener(new View.OnClickListener() {
940 @Override
941
David Brown8373b452011-06-20 12:38:45 -0700942 public void onClick(View v) {
943 takeEmergencyCallAction();
944 }
945 });
946 } else {
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700947 emergencyCall.setVisibility(View.GONE);
David Brown8373b452011-06-20 12:38:45 -0700948 return;
949 }
950
David Brown8373b452011-06-20 12:38:45 -0700951 int textId;
Tyler Gunn3e71b192014-09-10 15:21:33 -0700952 if (getTelecomManager().isInCall()) {
Paul Lawrence89c75702014-07-11 07:34:44 -0700953 // Show "return to call"
David Brown8373b452011-06-20 12:38:45 -0700954 textId = R.string.cryptkeeper_return_to_call;
David Brown8373b452011-06-20 12:38:45 -0700955 } else {
956 textId = R.string.cryptkeeper_emergency_call;
David Brown8373b452011-06-20 12:38:45 -0700957 }
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700958 emergencyCall.setText(textId);
David Brown8373b452011-06-20 12:38:45 -0700959 }
960
961 private boolean isEmergencyCallCapable() {
962 return getResources().getBoolean(com.android.internal.R.bool.config_voice_capable);
963 }
964
965 private void takeEmergencyCallAction() {
Tyler Gunn3e71b192014-09-10 15:21:33 -0700966 TelecomManager telecomManager = getTelecomManager();
967 if (telecomManager.isInCall()) {
968 telecomManager.showInCallScreen(false /* showDialpad */);
David Brown8373b452011-06-20 12:38:45 -0700969 } else {
970 launchEmergencyDialer();
971 }
972 }
973
David Brown8373b452011-06-20 12:38:45 -0700974
975 private void launchEmergencyDialer() {
Vikram Aggarwalbfa3a642012-03-29 14:07:22 -0700976 final Intent intent = new Intent(ACTION_EMERGENCY_DIAL);
David Brown8373b452011-06-20 12:38:45 -0700977 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
978 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
Paul Lawrence5a70f052014-06-13 11:09:55 -0700979 setBackFunctionality(true);
David Brown8373b452011-06-20 12:38:45 -0700980 startActivity(intent);
981 }
Vikram Aggarwald1147252012-05-08 13:52:30 -0700982
Santos Cordon3afbdf02014-05-29 21:48:16 -0700983 private TelephonyManager getTelephonyManager() {
984 return (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
985 }
986
Tyler Gunn3e71b192014-09-10 15:21:33 -0700987 private TelecomManager getTelecomManager() {
988 return (TelecomManager) getSystemService(Context.TELECOM_SERVICE);
Santos Cordon35230e92014-07-07 16:25:10 -0700989 }
990
Vikram Aggarwald1147252012-05-08 13:52:30 -0700991 /**
992 * Listen to key events so we can disable sounds when we get a keyinput in EditText.
993 */
994 private void delayAudioNotification() {
Vikram Aggarwald1147252012-05-08 13:52:30 -0700995 mNotificationCountdown = 20;
996 }
997
998 @Override
999 public boolean onKey(View v, int keyCode, KeyEvent event) {
1000 delayAudioNotification();
1001 return false;
1002 }
1003
1004 @Override
1005 public boolean onTouch(View v, MotionEvent event) {
1006 delayAudioNotification();
1007 return false;
1008 }
1009
1010 @Override
1011 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
1012 return;
1013 }
1014
1015 @Override
1016 public void onTextChanged(CharSequence s, int start, int before, int count) {
1017 delayAudioNotification();
1018 }
1019
1020 @Override
1021 public void afterTextChanged(Editable s) {
1022 return;
1023 }
David Brown8373b452011-06-20 12:38:45 -07001024}