/
LockPatternKeyguardView.java
1430 lines (1250 loc) · 54.6 KB
/
LockPatternKeyguardView.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
import com.android.internal.R;
import com.android.internal.policy.impl.KeyguardUpdateMonitor.InfoCallback;
import com.android.internal.policy.impl.KeyguardUpdateMonitor.InfoCallbackImpl;
import com.android.internal.policy.impl.LockPatternKeyguardView.UnlockMode;
import com.android.internal.policy.IFaceLockCallback;
import com.android.internal.policy.IFaceLockInterface;
import com.android.internal.telephony.IccCard;
import com.android.internal.widget.LockPatternUtils;
import com.android.internal.widget.LockScreenWidgetCallback;
import com.android.internal.widget.LockScreenWidgetInterface;
import com.android.internal.widget.TransportControlView;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.AlertDialog;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.PixelFormat;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.IBinder;
import android.os.Parcelable;
import android.os.PowerManager;
import android.os.RemoteException;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.util.Slog;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityManager;
import java.io.IOException;
/**
* The host view for all of the screens of the pattern unlock screen. There are
* two {@link Mode}s of operation, lock and unlock. This will show the appropriate
* screen, and listen for callbacks via
* {@link com.android.internal.policy.impl.KeyguardScreenCallback}
* from the current screen.
*
* This view, in turn, communicates back to
* {@link com.android.internal.policy.impl.KeyguardViewManager}
* via its {@link com.android.internal.policy.impl.KeyguardViewCallback}, as appropriate.
*/
public class LockPatternKeyguardView extends KeyguardViewBase implements Handler.Callback {
private static final int TRANSPORT_USERACTIVITY_TIMEOUT = 10000;
static final boolean DEBUG_CONFIGURATION = false;
// time after launching EmergencyDialer before the screen goes blank.
private static final int EMERGENCY_CALL_TIMEOUT = 10000;
// intent action for launching emergency dialer activity.
static final String ACTION_EMERGENCY_DIAL = "com.android.phone.EmergencyDialer.DIAL";
private static final boolean DEBUG = false;
private static final String TAG = "LockPatternKeyguardView";
private final KeyguardUpdateMonitor mUpdateMonitor;
private final KeyguardWindowController mWindowController;
private View mLockScreen;
private View mUnlockScreen;
private boolean mScreenOn;
private boolean mWindowFocused = false;
private boolean mEnableFallback = false; // assume no fallback UI until we know better
private boolean mShowLockBeforeUnlock = false;
// The following were added to support FaceLock
private IFaceLockInterface mFaceLockService;
private boolean mBoundToFaceLockService = false;
private View mFaceLockAreaView;
private boolean mFaceLockServiceRunning = false;
private final Object mFaceLockServiceRunningLock = new Object();
private final Object mFaceLockStartupLock = new Object();
private Handler mHandler;
private final int MSG_SHOW_FACELOCK_AREA_VIEW = 0;
private final int MSG_HIDE_FACELOCK_AREA_VIEW = 1;
// Long enough to stay visible while dialer comes up
// Short enough to not be visible if the user goes back immediately
private final int FACELOCK_VIEW_AREA_EMERGENCY_DIALER_TIMEOUT = 1000;
// Long enough to stay visible while the service starts
// Short enough to not have to wait long for backup if service fails to start or crashes
// The service can take a couple of seconds to start on the first try after boot
private final int FACELOCK_VIEW_AREA_SERVICE_TIMEOUT = 3000;
// So the user has a consistent amount of time when brought to the backup method from FaceLock
private final int BACKUP_LOCK_TIMEOUT = 5000;
private boolean mRequiresSim;
//True if we have some sort of overlay on top of the Lockscreen
//Also true if we've activated a phone call, either emergency dialing or incoming
//This resets when the phone is turned off with no current call
private boolean mHasOverlay;
//True if a dialog is currently displaying on top of this window
//Unlike other overlays, this does not close with a power button cycle
private boolean mHasDialog = false;
//True if this device is currently plugged in
private boolean mPluggedIn;
// The music control widget
private TransportControlView mTransportControlView;
private Parcelable mSavedState;
/**
* Either a lock screen (an informational keyguard screen), or an unlock
* screen (a means for unlocking the device) is shown at any given time.
*/
enum Mode {
LockScreen,
UnlockScreen
}
/**
* The different types screens available for {@link Mode#UnlockScreen}.
* @see com.android.internal.policy.impl.LockPatternKeyguardView#getUnlockMode()
*/
enum UnlockMode {
/**
* Unlock by drawing a pattern.
*/
Pattern,
/**
* Unlock by entering a sim pin.
*/
SimPin,
/**
* Unlock by entering a sim puk.
*/
SimPuk,
/**
* Unlock by entering an account's login and password.
*/
Account,
/**
* Unlock by entering a password or PIN
*/
Password,
/**
* Unknown (uninitialized) value
*/
Unknown
}
/**
* The current mode.
*/
private Mode mMode = Mode.LockScreen;
/**
* Keeps track of what mode the current unlock screen is (cached from most recent computation in
* {@link #getUnlockMode}).
*/
private UnlockMode mUnlockScreenMode = UnlockMode.Unknown;
private boolean mForgotPattern;
/**
* If true, it means we are in the process of verifying that the user
* can get past the lock screen per {@link #verifyUnlock()}
*/
private boolean mIsVerifyUnlockOnly = false;
/**
* Used to lookup the state of the lock pattern
*/
private final LockPatternUtils mLockPatternUtils;
/**
* The current configuration.
*/
private Configuration mConfiguration;
private Runnable mRecreateRunnable = new Runnable() {
public void run() {
updateScreen(mMode, true);
restoreWidgetState();
}
};
private LockScreenWidgetCallback mWidgetCallback = new LockScreenWidgetCallback() {
public void userActivity(View self) {
mKeyguardScreenCallback.pokeWakelock(TRANSPORT_USERACTIVITY_TIMEOUT);
}
public void requestShow(View view) {
if (DEBUG) Log.v(TAG, "View " + view + " requested show transports");
view.setVisibility(View.VISIBLE);
// TODO: examine all widgets to derive clock status
mUpdateMonitor.reportClockVisible(false);
// If there's not a bg protection view containing the transport, then show a black
// background. Otherwise, allow the normal background to show.
if (findViewById(R.id.transport_bg_protect) == null) {
// TODO: We should disable the wallpaper instead
setBackgroundColor(0xff000000);
} else {
resetBackground();
}
}
public void requestHide(View view) {
if (DEBUG) Log.v(TAG, "View " + view + " requested hide transports");
view.setVisibility(View.GONE);
// TODO: examine all widgets to derive clock status
mUpdateMonitor.reportClockVisible(true);
resetBackground();
}
public boolean isVisible(View self) {
// TODO: this should be up to the lockscreen to determine if the view
// is currently showing. The idea is it can be used for the widget to
// avoid doing work if it's not visible. For now just returns the view's
// actual visibility.
return self.getVisibility() == View.VISIBLE;
}
};
/**
* @return Whether we are stuck on the lock screen because the sim is
* missing.
*/
private boolean stuckOnLockScreenBecauseSimMissing() {
return mRequiresSim
&& (!mUpdateMonitor.isDeviceProvisioned())
&& (mUpdateMonitor.getSimState() == IccCard.State.ABSENT ||
mUpdateMonitor.getSimState() == IccCard.State.PERM_DISABLED);
}
/**
* The current {@link KeyguardScreen} will use this to communicate back to us.
*/
KeyguardScreenCallback mKeyguardScreenCallback = new KeyguardScreenCallback() {
public void goToLockScreen() {
mForgotPattern = false;
if (mIsVerifyUnlockOnly) {
// navigating away from unlock screen during verify mode means
// we are done and the user failed to authenticate.
mIsVerifyUnlockOnly = false;
getCallback().keyguardDone(false);
} else {
updateScreen(Mode.LockScreen, false);
}
}
public void goToUnlockScreen() {
final IccCard.State simState = mUpdateMonitor.getSimState();
if (stuckOnLockScreenBecauseSimMissing()
|| (simState == IccCard.State.PUK_REQUIRED
&& !mLockPatternUtils.isPukUnlockScreenEnable())){
// stuck on lock screen when sim missing or
// puk'd but puk unlock screen is disabled
return;
}
if (!isSecure()) {
getCallback().keyguardDone(true);
} else {
updateScreen(Mode.UnlockScreen, false);
}
}
public void forgotPattern(boolean isForgotten) {
if (mEnableFallback) {
mForgotPattern = isForgotten;
updateScreen(Mode.UnlockScreen, false);
}
}
public boolean isSecure() {
return LockPatternKeyguardView.this.isSecure();
}
public boolean isVerifyUnlockOnly() {
return mIsVerifyUnlockOnly;
}
public void recreateMe(Configuration config) {
removeCallbacks(mRecreateRunnable);
post(mRecreateRunnable);
}
public void takeEmergencyCallAction() {
mHasOverlay = true;
// Continue showing FaceLock area until dialer comes up or call is resumed
if (usingFaceLock() && mFaceLockServiceRunning) {
showFaceLockAreaWithTimeout(FACELOCK_VIEW_AREA_EMERGENCY_DIALER_TIMEOUT);
}
// FaceLock must be stopped if it is running when emergency call is pressed
stopAndUnbindFromFaceLock();
pokeWakelock(EMERGENCY_CALL_TIMEOUT);
if (TelephonyManager.getDefault().getCallState()
== TelephonyManager.CALL_STATE_OFFHOOK) {
mLockPatternUtils.resumeCall();
} else {
Intent intent = new Intent(ACTION_EMERGENCY_DIAL);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
getContext().startActivity(intent);
}
}
public void pokeWakelock() {
getCallback().pokeWakelock();
}
public void pokeWakelock(int millis) {
getCallback().pokeWakelock(millis);
}
public void keyguardDone(boolean authenticated) {
getCallback().keyguardDone(authenticated);
mSavedState = null; // clear state so we re-establish when locked again
}
public void keyguardDoneDrawing() {
// irrelevant to keyguard screen, they shouldn't be calling this
}
public void reportFailedUnlockAttempt() {
mUpdateMonitor.reportFailedAttempt();
final int failedAttempts = mUpdateMonitor.getFailedAttempts();
if (DEBUG) Log.d(TAG, "reportFailedPatternAttempt: #" + failedAttempts +
" (enableFallback=" + mEnableFallback + ")");
final boolean usingPattern = mLockPatternUtils.getKeyguardStoredPasswordQuality()
== DevicePolicyManager.PASSWORD_QUALITY_SOMETHING;
final int failedAttemptsBeforeWipe = mLockPatternUtils.getDevicePolicyManager()
.getMaximumFailedPasswordsForWipe(null);
final int failedAttemptWarning = LockPatternUtils.FAILED_ATTEMPTS_BEFORE_RESET
- LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT;
final int remainingBeforeWipe = failedAttemptsBeforeWipe > 0 ?
(failedAttemptsBeforeWipe - failedAttempts)
: Integer.MAX_VALUE; // because DPM returns 0 if no restriction
if (remainingBeforeWipe < LockPatternUtils.FAILED_ATTEMPTS_BEFORE_WIPE_GRACE) {
// If we reach this code, it means the user has installed a DevicePolicyManager
// that requests device wipe after N attempts. Once we get below the grace
// period, we'll post this dialog every time as a clear warning until the
// bombshell hits and the device is wiped.
if (remainingBeforeWipe > 0) {
showAlmostAtWipeDialog(failedAttempts, remainingBeforeWipe);
} else {
// Too many attempts. The device will be wiped shortly.
Slog.i(TAG, "Too many unlock attempts; device will be wiped!");
showWipeDialog(failedAttempts);
}
} else {
boolean showTimeout =
(failedAttempts % LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT) == 0;
if (usingPattern && mEnableFallback) {
if (failedAttempts == failedAttemptWarning) {
showAlmostAtAccountLoginDialog();
showTimeout = false; // don't show both dialogs
} else if (failedAttempts >= LockPatternUtils.FAILED_ATTEMPTS_BEFORE_RESET) {
mLockPatternUtils.setPermanentlyLocked(true);
updateScreen(mMode, false);
// don't show timeout dialog because we show account unlock screen next
showTimeout = false;
}
}
if (showTimeout) {
showTimeoutDialog();
}
}
mLockPatternUtils.reportFailedPasswordAttempt();
}
public boolean doesFallbackUnlockScreenExist() {
return mEnableFallback;
}
public void reportSuccessfulUnlockAttempt() {
mLockPatternUtils.reportSuccessfulPasswordAttempt();
}
};
/**
* @param context Used to inflate, and create views.
* @param callback Keyguard callback object for pokewakelock(), etc.
* @param updateMonitor Knows the state of the world, and passed along to each
* screen so they can use the knowledge, and also register for callbacks
* on dynamic information.
* @param lockPatternUtils Used to look up state of lock pattern.
*/
public LockPatternKeyguardView(
Context context, KeyguardViewCallback callback, KeyguardUpdateMonitor updateMonitor,
LockPatternUtils lockPatternUtils, KeyguardWindowController controller) {
super(context, callback);
mHandler = new Handler(this);
mConfiguration = context.getResources().getConfiguration();
mEnableFallback = false;
mRequiresSim = TextUtils.isEmpty(SystemProperties.get("keyguard.no_require_sim"));
mUpdateMonitor = updateMonitor;
mLockPatternUtils = lockPatternUtils;
mWindowController = controller;
mHasOverlay = false;
mPluggedIn = mUpdateMonitor.isDevicePluggedIn();
mScreenOn = ((PowerManager)context.getSystemService(Context.POWER_SERVICE)).isScreenOn();
mUpdateMonitor.registerInfoCallback(mInfoCallback);
/**
* We'll get key events the current screen doesn't use. see
* {@link KeyguardViewBase#onKeyDown(int, android.view.KeyEvent)}
*/
setFocusableInTouchMode(true);
setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
updateScreen(getInitialMode(), false);
maybeEnableFallback(context);
}
private class AccountAnalyzer implements AccountManagerCallback<Bundle> {
private final AccountManager mAccountManager;
private final Account[] mAccounts;
private int mAccountIndex;
private AccountAnalyzer(AccountManager accountManager) {
mAccountManager = accountManager;
mAccounts = accountManager.getAccountsByType("com.google");
}
private void next() {
// if we are ready to enable the fallback or if we depleted the list of accounts
// then finish and get out
if (mEnableFallback || mAccountIndex >= mAccounts.length) {
if (mUnlockScreen == null) {
if (DEBUG) Log.w(TAG, "no unlock screen when trying to enable fallback");
} else if (mUnlockScreen instanceof PatternUnlockScreen) {
((PatternUnlockScreen)mUnlockScreen).setEnableFallback(mEnableFallback);
}
return;
}
// lookup the confirmCredentials intent for the current account
mAccountManager.confirmCredentials(mAccounts[mAccountIndex], null, null, this, null);
}
public void start() {
mEnableFallback = false;
mAccountIndex = 0;
next();
}
public void run(AccountManagerFuture<Bundle> future) {
try {
Bundle result = future.getResult();
if (result.getParcelable(AccountManager.KEY_INTENT) != null) {
mEnableFallback = true;
}
} catch (OperationCanceledException e) {
// just skip the account if we are unable to query it
} catch (IOException e) {
// just skip the account if we are unable to query it
} catch (AuthenticatorException e) {
// just skip the account if we are unable to query it
} finally {
mAccountIndex++;
next();
}
}
}
private void maybeEnableFallback(Context context) {
// Ask the account manager if we have an account that can be used as a
// fallback in case the user forgets his pattern.
AccountAnalyzer accountAnalyzer = new AccountAnalyzer(AccountManager.get(context));
accountAnalyzer.start();
}
// TODO:
// This overloaded method was added to workaround a race condition in the framework between
// notification for orientation changed, layout() and switching resources. This code attempts
// to avoid drawing the incorrect layout while things are in transition. The method can just
// be removed once the race condition is fixed. See bugs 2262578 and 2292713.
@Override
protected void dispatchDraw(Canvas canvas) {
if (DEBUG) Log.v(TAG, "*** dispatchDraw() time: " + SystemClock.elapsedRealtime());
super.dispatchDraw(canvas);
}
@Override
public void reset() {
mIsVerifyUnlockOnly = false;
mForgotPattern = false;
post(mRecreateRunnable);
}
@Override
public void onScreenTurnedOff() {
if (DEBUG) Log.d(TAG, "screen off");
mScreenOn = false;
mForgotPattern = false;
mHasOverlay = mUpdateMonitor.getPhoneState() != TelephonyManager.CALL_STATE_IDLE ||
mHasDialog;
// Emulate activity life-cycle for both lock and unlock screen.
if (mLockScreen != null) {
((KeyguardScreen) mLockScreen).onPause();
}
if (mUnlockScreen != null) {
((KeyguardScreen) mUnlockScreen).onPause();
}
saveWidgetState();
// When screen is turned off, need to unbind from FaceLock service if using FaceLock
stopAndUnbindFromFaceLock();
}
/** When screen is turned on and focused, need to bind to FaceLock service if we are using
* FaceLock, but only if we're not dealing with a call
*/
private void activateFaceLockIfAble() {
final boolean tooManyFaceUnlockTries = mUpdateMonitor.getMaxFaceUnlockAttemptsReached();
final int failedBackupAttempts = mUpdateMonitor.getFailedAttempts();
final boolean backupIsTimedOut =
(failedBackupAttempts >= LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT);
if (tooManyFaceUnlockTries) Log.i(TAG, "tooManyFaceUnlockTries: " + tooManyFaceUnlockTries);
if (mUpdateMonitor.getPhoneState() == TelephonyManager.CALL_STATE_IDLE
&& usingFaceLock()
&& !mHasOverlay
&& !tooManyFaceUnlockTries
&& !backupIsTimedOut) {
bindToFaceLock();
// Show FaceLock area, but only for a little bit so lockpattern will become visible if
// FaceLock fails to start or crashes
showFaceLockAreaWithTimeout(FACELOCK_VIEW_AREA_SERVICE_TIMEOUT);
// When switching between portrait and landscape view while FaceLock is running, the
// screen will eventually go dark unless we poke the wakelock when FaceLock is
// restarted
mKeyguardScreenCallback.pokeWakelock();
} else {
hideFaceLockArea();
}
}
@Override
public void onScreenTurnedOn() {
if (DEBUG) Log.d(TAG, "screen on");
boolean runFaceLock = false;
//Make sure to start facelock iff the screen is both on and focused
synchronized(mFaceLockStartupLock) {
mScreenOn = true;
runFaceLock = mWindowFocused;
}
show();
restoreWidgetState();
if (runFaceLock) activateFaceLockIfAble();
}
private void saveWidgetState() {
if (mTransportControlView != null) {
if (DEBUG) Log.v(TAG, "Saving widget state");
mSavedState = mTransportControlView.onSaveInstanceState();
}
}
private void restoreWidgetState() {
if (mTransportControlView != null) {
if (DEBUG) Log.v(TAG, "Restoring widget state");
if (mSavedState != null) {
mTransportControlView.onRestoreInstanceState(mSavedState);
}
}
}
/** Unbind from facelock if something covers this window (such as an alarm)
* bind to facelock if the lockscreen window just came into focus, and the screen is on
*/
@Override
public void onWindowFocusChanged (boolean hasWindowFocus) {
if (DEBUG) Log.d(TAG, hasWindowFocus ? "focused" : "unfocused");
boolean runFaceLock = false;
//Make sure to start facelock iff the screen is both on and focused
synchronized(mFaceLockStartupLock) {
if(mScreenOn && !mWindowFocused) runFaceLock = hasWindowFocus;
mWindowFocused = hasWindowFocus;
}
if(!hasWindowFocus) {
mHasOverlay = true;
stopAndUnbindFromFaceLock();
hideFaceLockArea();
} else {
mHasDialog = false;
if (runFaceLock) activateFaceLockIfAble();
}
}
@Override
public void show() {
// Emulate activity life-cycle for both lock and unlock screen.
if (mLockScreen != null) {
((KeyguardScreen) mLockScreen).onResume();
}
if (mUnlockScreen != null) {
((KeyguardScreen) mUnlockScreen).onResume();
}
if (usingFaceLock() && !mHasOverlay) {
// Note that show() gets called before the screen turns off to set it up for next time
// it is turned on. We don't want to set a timeout on the FaceLock area here because it
// may be gone by the time the screen is turned on again. We set the timeout when the
// screen turns on instead.
showFaceLockArea();
} else {
hideFaceLockArea();
}
}
private void recreateLockScreen() {
if (mLockScreen != null) {
((KeyguardScreen) mLockScreen).onPause();
((KeyguardScreen) mLockScreen).cleanUp();
removeView(mLockScreen);
}
mLockScreen = createLockScreen();
mLockScreen.setVisibility(View.INVISIBLE);
addView(mLockScreen);
}
private void recreateUnlockScreen(UnlockMode unlockMode) {
if (mUnlockScreen != null) {
((KeyguardScreen) mUnlockScreen).onPause();
((KeyguardScreen) mUnlockScreen).cleanUp();
removeView(mUnlockScreen);
}
mUnlockScreen = createUnlockScreenFor(unlockMode);
mUnlockScreen.setVisibility(View.INVISIBLE);
addView(mUnlockScreen);
}
@Override
protected void onDetachedFromWindow() {
mUpdateMonitor.removeCallback(mInfoCallback);
removeCallbacks(mRecreateRunnable);
// When view is hidden, need to unbind from FaceLock service if we are using FaceLock
// e.g., when device becomes unlocked
stopAndUnbindFromFaceLock();
super.onDetachedFromWindow();
}
protected void onConfigurationChanged(Configuration newConfig) {
Resources resources = getResources();
mShowLockBeforeUnlock = resources.getBoolean(R.bool.config_enableLockBeforeUnlockScreen);
mConfiguration = newConfig;
if (DEBUG_CONFIGURATION) Log.v(TAG, "**** re-creating lock screen since config changed");
saveWidgetState();
removeCallbacks(mRecreateRunnable);
post(mRecreateRunnable);
}
InfoCallbackImpl mInfoCallback = new InfoCallbackImpl() {
/** When somebody plugs in or unplugs the device, we don't want to display faceunlock */
@Override
public void onRefreshBatteryInfo(boolean showBatteryInfo, boolean pluggedIn,
int batteryLevel) {
mHasOverlay |= mPluggedIn != pluggedIn;
mPluggedIn = pluggedIn;
//If it's already running, don't close it down: the unplug didn't start it
if (!mFaceLockServiceRunning) {
stopAndUnbindFromFaceLock();
hideFaceLockArea();
}
}
@Override
public void onClockVisibilityChanged() {
int visFlags = getSystemUiVisibility() & ~View.STATUS_BAR_DISABLE_CLOCK;
setSystemUiVisibility(visFlags
| (mUpdateMonitor.isClockVisible() ? View.STATUS_BAR_DISABLE_CLOCK : 0));
}
//We need to stop faceunlock when a phonecall comes in
@Override
public void onPhoneStateChanged(int phoneState) {
if (DEBUG) Log.d(TAG, "phone state: " + phoneState);
if(phoneState == TelephonyManager.CALL_STATE_RINGING) {
mHasOverlay = true;
stopAndUnbindFromFaceLock();
hideFaceLockArea();
}
}
@Override
public void onUserChanged(int userId) {
mLockPatternUtils.setCurrentUser(userId);
updateScreen(getInitialMode(), true);
}
};
@Override
protected boolean dispatchHoverEvent(MotionEvent event) {
// Do not let the screen to get locked while the user is disabled and touch
// exploring. A blind user will need significantly more time to find and
// interact with the lock screen views.
AccessibilityManager accessibilityManager = AccessibilityManager.getInstance(mContext);
if (accessibilityManager.isEnabled() && accessibilityManager.isTouchExplorationEnabled()) {
getCallback().pokeWakelock();
}
return super.dispatchHoverEvent(event);
}
@Override
public void wakeWhenReadyTq(int keyCode) {
if (DEBUG) Log.d(TAG, "onWakeKey");
if (keyCode == KeyEvent.KEYCODE_MENU && isSecure() && (mMode == Mode.LockScreen)
&& (mUpdateMonitor.getSimState() != IccCard.State.PUK_REQUIRED)) {
if (DEBUG) Log.d(TAG, "switching screens to unlock screen because wake key was MENU");
updateScreen(Mode.UnlockScreen, false);
getCallback().pokeWakelock();
} else {
if (DEBUG) Log.d(TAG, "poking wake lock immediately");
getCallback().pokeWakelock();
}
}
@Override
public void verifyUnlock() {
if (!isSecure()) {
// non-secure keyguard screens are successfull by default
getCallback().keyguardDone(true);
} else if (mUnlockScreenMode != UnlockMode.Pattern
&& mUnlockScreenMode != UnlockMode.Password) {
// can only verify unlock when in pattern/password mode
getCallback().keyguardDone(false);
} else {
// otherwise, go to the unlock screen, see if they can verify it
mIsVerifyUnlockOnly = true;
updateScreen(Mode.UnlockScreen, false);
}
}
@Override
public void cleanUp() {
if (mLockScreen != null) {
((KeyguardScreen) mLockScreen).onPause();
((KeyguardScreen) mLockScreen).cleanUp();
this.removeView(mLockScreen);
mLockScreen = null;
}
if (mUnlockScreen != null) {
((KeyguardScreen) mUnlockScreen).onPause();
((KeyguardScreen) mUnlockScreen).cleanUp();
this.removeView(mUnlockScreen);
mUnlockScreen = null;
}
mUpdateMonitor.removeCallback(this);
if (mFaceLockService != null) {
try {
mFaceLockService.unregisterCallback(mFaceLockCallback);
} catch (RemoteException e) {
// Not much we can do
}
stopFaceLock();
mFaceLockService = null;
}
}
private boolean isSecure() {
UnlockMode unlockMode = getUnlockMode();
boolean secure = false;
switch (unlockMode) {
case Pattern:
secure = mLockPatternUtils.isLockPatternEnabled();
break;
case SimPin:
secure = mUpdateMonitor.getSimState() == IccCard.State.PIN_REQUIRED;
break;
case SimPuk:
secure = mUpdateMonitor.getSimState() == IccCard.State.PUK_REQUIRED;
break;
case Account:
secure = true;
break;
case Password:
secure = mLockPatternUtils.isLockPasswordEnabled();
break;
case Unknown:
// This means no security is set up
break;
default:
throw new IllegalStateException("unknown unlock mode " + unlockMode);
}
return secure;
}
private void updateScreen(Mode mode, boolean force) {
if (DEBUG_CONFIGURATION) Log.v(TAG, "**** UPDATE SCREEN: mode=" + mode
+ " last mode=" + mMode + ", force = " + force, new RuntimeException());
mMode = mode;
// Re-create the lock screen if necessary
if (mode == Mode.LockScreen || mShowLockBeforeUnlock) {
if (force || mLockScreen == null) {
recreateLockScreen();
}
}
// Re-create the unlock screen if necessary. This is primarily required to properly handle
// SIM state changes. This typically happens when this method is called by reset()
final UnlockMode unlockMode = getUnlockMode();
if (mode == Mode.UnlockScreen && unlockMode != UnlockMode.Unknown) {
if (force || mUnlockScreen == null || unlockMode != mUnlockScreenMode) {
boolean restartFaceLock = stopFaceLockIfRunning();
recreateUnlockScreen(unlockMode);
if (restartFaceLock) activateFaceLockIfAble();
}
}
// visibleScreen should never be null
final View goneScreen = (mode == Mode.LockScreen) ? mUnlockScreen : mLockScreen;
final View visibleScreen = (mode == Mode.LockScreen) ? mLockScreen : mUnlockScreen;
// do this before changing visibility so focus isn't requested before the input
// flag is set
mWindowController.setNeedsInput(((KeyguardScreen)visibleScreen).needsInput());
if (DEBUG_CONFIGURATION) {
Log.v(TAG, "Gone=" + goneScreen);
Log.v(TAG, "Visible=" + visibleScreen);
}
if (mScreenOn) {
if (goneScreen != null && goneScreen.getVisibility() == View.VISIBLE) {
((KeyguardScreen) goneScreen).onPause();
}
if (visibleScreen.getVisibility() != View.VISIBLE) {
((KeyguardScreen) visibleScreen).onResume();
}
}
if (goneScreen != null) {
goneScreen.setVisibility(View.GONE);
}
visibleScreen.setVisibility(View.VISIBLE);
requestLayout();
if (!visibleScreen.requestFocus()) {
throw new IllegalStateException("keyguard screen must be able to take "
+ "focus when shown " + visibleScreen.getClass().getCanonicalName());
}
}
View createLockScreen() {
View lockView = new LockScreen(
mContext,
mConfiguration,
mLockPatternUtils,
mUpdateMonitor,
mKeyguardScreenCallback);
initializeTransportControlView(lockView);
return lockView;
}
View createUnlockScreenFor(UnlockMode unlockMode) {
View unlockView = null;
if (DEBUG) Log.d(TAG,
"createUnlockScreenFor(" + unlockMode + "): mEnableFallback=" + mEnableFallback);
if (unlockMode == UnlockMode.Pattern) {
PatternUnlockScreen view = new PatternUnlockScreen(
mContext,
mConfiguration,
mLockPatternUtils,
mUpdateMonitor,
mKeyguardScreenCallback,
mUpdateMonitor.getFailedAttempts());
view.setEnableFallback(mEnableFallback);
unlockView = view;
} else if (unlockMode == UnlockMode.SimPuk) {
unlockView = new SimPukUnlockScreen(
mContext,
mConfiguration,
mUpdateMonitor,
mKeyguardScreenCallback,
mLockPatternUtils);
} else if (unlockMode == UnlockMode.SimPin) {
unlockView = new SimUnlockScreen(
mContext,
mConfiguration,
mUpdateMonitor,
mKeyguardScreenCallback,
mLockPatternUtils);
} else if (unlockMode == UnlockMode.Account) {
try {
unlockView = new AccountUnlockScreen(
mContext,
mConfiguration,
mUpdateMonitor,
mKeyguardScreenCallback,
mLockPatternUtils);
} catch (IllegalStateException e) {
Log.i(TAG, "Couldn't instantiate AccountUnlockScreen"
+ " (IAccountsService isn't available)");
// TODO: Need a more general way to provide a
// platform-specific fallback UI here.
// For now, if we can't display the account login
// unlock UI, just bring back the regular "Pattern" unlock mode.
// (We do this by simply returning a regular UnlockScreen
// here. This means that the user will still see the
// regular pattern unlock UI, regardless of the value of
// mUnlockScreenMode or whether or not we're in the
// "permanently locked" state.)
return createUnlockScreenFor(UnlockMode.Pattern);
}
} else if (unlockMode == UnlockMode.Password) {
unlockView = new PasswordUnlockScreen(
mContext,
mConfiguration,
mLockPatternUtils,
mUpdateMonitor,
mKeyguardScreenCallback);
} else {
throw new IllegalArgumentException("unknown unlock mode " + unlockMode);
}
initializeTransportControlView(unlockView);
initializeFaceLockAreaView(unlockView); // Only shows view if FaceLock is enabled
mUnlockScreenMode = unlockMode;