Android4.4 锁屏流程梳理
刚毕业不久由于项目需要就接触到锁屏,从2.2到4.1都解过bug,也定制过一些功能。4.1之前的锁屏工作不难,但很费时间,因为它的逻辑,视图,资源分别分布在不同的路径下,就像散落在海边沙滩上的珠子,想串起来还是蛮费劲的。最开始时锁屏就是改个字段也要全编译生成img。后来新技能get,会针对修改的地方进行单编译,但每次编译jar,导入手机,重启看效果也是不方便的。
一年前把锁屏交出去就没有再看过了,前些日子自己的谷歌四太子升到4.4,发现锁屏有很大变化,可以左右滑页,添加删除widget,添加删除分页。简直就是一个简化版的launcher。很好奇google是怎么改变的,于是费了很大的劲拉了google的最新源码。在android 4.4中这个模块的改动简直是巨大,这里略作整理。
1.文件目录:
a,锁屏代理是在Frameworks/base/policy/src/com/android/internal/policy/impl/keyguard下:
b,整个工程应用在framework/package下,结构和功能现在都和 systemUI类似:
c,keyguard的对外接口Frameworks/base/core/java/android/app/keyguardManager.java:
android4.2前做一些第三方锁屏软件都会用到该服务接口来控制系统锁屏(比如禁止系统锁屏),现在该接口已经不建议使用了,有更好的做法:
[java]
view plain
copy
1. /**
2. * @deprecated使用{@link android.view.WindowManager.LayoutParams#FLAG_DISMISS_KEYGUARD}
3. * and/or {@link android.view.WindowManager.LayoutParams#FLAG_SHOW_WHEN_LOCKED}
4. * 来代替; 利用该方式可以使应用达到禁用锁屏的效果而不需要额外的权限申请。this allows you to
5. * Enables you to lock or unlock thekeyboard. Get an instance of this class by
6. * calling {@link android.content.Context#getSystemService(java.lang.String)Context.getSystemService()}.
7. * This class is wrapped by {@link android.app.KeyguardManagerKeyguardManager}.
8. * @param tag A tag that informallyidentifies who you are (for debugging who
9. * is disabling he keyguard).
10. *
11. * @return A {@link KeyguardLock} handle to use todisable and reenable the
12. * keyguard.
13. */
14. @Deprecated
15. public KeyguardLock newKeyguardLock(Stringtag) {
16. return new KeyguardLock(tag);
17. }
Keyguard锁屏流程图
Keyguard锁屏view层次图:
Keyguard锁屏重要类分析:
1.PhoneWindowManager.java
这个类很厉害也很重要,它由WindowManagerService派生,处理了phone的顶层逻辑,主要有以下几块:
a) 横竖屏处理(屏幕旋转等)
[java] view plain copy
1. publicvoidsetCurrentOrientationLw(intnewOrientation){
2. synchronized (mLock){
3. if (newOrientation != mCurrentAppOrientation) {
4. mCurrentAppOrientation = newOrientation;
5. updateOrientationListenerLp();
6. }
7. }
8. }
b) 是否显示状态条或者navigation_bar。
[java] view plain copy
1. privateintupdateSystemUiVisibilityLw() {
2. // If there is no window focused,there will be nobody to handle the events
3. // anyway, so just hang on inwhatever state we're in until things settle down.
4. WindowState win = mFocusedWindow != null ? mFocusedWindow :mTopFullscreenOpaqueWindowState;
5. if (win == null){
6. return 0;
7. }
8. if (win.getAttrs().type == TYPE_KEYGUARD&&mHideLockScreen == true) {
9. // We are updating at a pointwhere the keyguard has gotten
10. // focus, but we were last in astate where the top window is
11. // hiding it. This is probably because the keyguardas been
12. // shown while the top window wasdisplayed, so we want to ignore
13. // it here because this is just avery transient change and it
14. // will quickly lose focus once itcorrectly gets hidden.
15. return 0;
16. }
17.
18. inttmpVisibility = win.getSystemUiVisibility()
19. & ~mResettingSystemUiFlags
20. & ~mForceClearedSystemUiFlags;
21. if (mForcingShowNavBar&&win.getSurfaceLayer()<mForcingShowNavBarLayer) {
22. tmpVisibility&= ~View.SYSTEM_UI_CLEARABLE_FLAGS;
23. }
24. finalint visibility = updateSystemBarsLw(win,mLastSystemUiFlags,tmpVisibility);
25. finalint diff = visibility ^ mLastSystemUiFlags;
26. finalbooleanneedsMenu = win.getNeedsMenuLw(mTopFullscreenOpaqueWindowState);
27. if (diff == 0 &&mLastFocusNeedsMenu == needsMenu
28. &&mFocusedApp ==win.getAppToken()) {
29. return 0;
30. }
31. mLastSystemUiFlags = visibility;
32. mLastFocusNeedsMenu = needsMenu;
33. mFocusedApp = win.getAppToken();
34. mHandler.post(new Runnable() {
35. @Override
36. publicvoid run() {
37. try {
38. IStatusBarServicestatusbar = getStatusBarService();
39. if (statusbar != null) {
40. statusbar.setSystemUiVisibility(visibility,0xffffffff);
41. statusbar.topAppWindowChanged(needsMenu);
42. }
43. catch (RemoteException e) {
44. // re-acquire status bar servicenext time it is needed.
45. mStatusBarService = null;
46. }
47. }
48. });
49. return diff;
50. }
c) 各种按键事件的拦截和分发(比如长按home键)
Home键的事件是在phonewindow这一层就拦截的,所以一般情况应用本身无法正常拦截该事件。
[java] view plain copy
1. privatevoidhandleLongPressOnHome() {
2. if (mLongPressOnHomeBehavior != LONG_PRESS_HOME_NOTHING) {
3. mHomeConsumed = true;
4. performHapticFeedbackLw(null,HapticFeedbackConstants.LONG_PRESS, false);
5.
6. if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI) {
7. toggleRecentApps();
8. } elseif (mLongPressOnHomeBehavior == LONG_PRESS_HOME_ASSIST){
9. launchAssistAction();
10. }
11. }
12. }
d) 锁屏事件处理和响应
[java] view plain copy
1. publicvoidsystemReady() {
2. if (!mHeadless){
3. mKeyguardDelegate = newKeyguardServiceDelegate(mContext, null);
4. mKeyguardDelegate.onSystemReady();
5. }
6. synchronized (mLock){
7. updateOrientationListenerLp();
8. mSystemReady = true;
9. mHandler.post(new Runnable() {
10. @Override
11. publicvoid run() {
12. updateSettings();
13. }
14. });
15. }
16. }
2.KeyguardServiceDelegate.java和KeyguardServiceWrapper.java
代理类里面有一个Scrim视图在keyguard崩溃时显示。包装类就是对keyguardService的简单包装,最终把调度都会传给keyguardService。
3.keyguardService.java
上面一再说到该类,那么它有啥出众的地方呢,其实它就是keyguard的入口,锁屏所有的往生都因它而起,这个类很简单,实例化了一个IKeyguardService.Stub供其他类bindservice时调用,需要特别注意的是整个keyguard的核心实力派KeyguardViewMediator在这里诞生了。
4.KeyguardViewMediator.java
字面上的意思是keyguard视图调度者,功能上是负责处理keyguard视图的事件,比如完成锁屏和解锁这些动作的视图响应,它作为一个位高权重的调度使当然不会亲手去做这些,它有个得力干将KeyguardviewManager,所有的大小任务都会放权给它。
[java] view plain copy
1. /**
2. *有关锁屏请求的调度者。包括锁屏状态的查询,power management事件影响锁屏是否应该被显示或者重置,特定的回调函数来
3. *通知windowmanager锁屏是什么时候显示,以及接受view视图传过来的消息表明已经成功完成解锁。
4. *请注意锁屏是在灭屏后立即被调用显示的。这样当你点亮屏幕,锁屏才能第一时间显示出来。
5. *例如外部事件调度锁屏视图流程:
6. *
7. *-灭屏动作-》重置锁屏并显示它为下次点亮屏幕做好准备。
8. *-锁屏很自然流畅的打开了-》如果他不是安全的,隐藏之。
9. *
10. *来自于锁屏视图的事件:
11. *-用户成功完成解锁条件-》隐藏锁屏视图,不再对输入事件进行拦截。
12. *请再注意:第三方应用通过条用power managment实例可以屏蔽系统的锁屏。
13. *
14. *线程和同步:
15. *该类是由WindowManagerPolicy创建并运行在它的线程里,锁屏UI也是这个类的构造函数里面产生。这个apis也可以被其他线程所调用。
16. *然而,这个类的方法手势同步的,同时任何一个锁屏视图都会发消息到handle来保证它是在锁屏UI线程里面执行的。
17. */
18.
19. public class KeyguardViewMediatorimplements KeyguardViewCallback,
20. KeyguardUpdateMonitor.InfoCallback,KeyguardUpdateMonitor.SimStateCallback {
21. private static final intKEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT = 30000;
22. /**
23. * This handler will be associated with the policy thread, which willalso
24. * be the UI thread of the keyguard. Since the apis of the policy, and therefore
25. * this class, can be called by other threads, any action that directly
26. * interacts with the keyguard ui should be posted to this handler,rather
27. * than called directly.
28. */
29. private Handler mHandler = new Handler() {
30. @Override
31. public void handleMessage(Message msg) {
32. switch (msg.what) {
33. case TIMEOUT:
34. handleTimeout(msg.arg1);
35. return ;
36. case SHOW:
37. handleShow();
38. return ;
39. case HIDE:
40. handleHide();
41. return ;
42. case RESET:
43. handleReset();
44. return ;
45. case VERIFY_UNLOCK:
46. handleVerifyUnlock();
47. return;
48. case NOTIFY_SCREEN_OFF:
49. handleNotifyScreenOff();
50. return;
51. case NOTIFY_SCREEN_ON:
52. handleNotifyScreenOn((KeyguardViewManager.ShowListener)msg.obj);
53. return;
54. case WAKE_WHEN_READY:
55. handleWakeWhenReady(msg.arg1);
56. return;
57. case KEYGUARD_DONE:
58. 0);
59. return;
60. case KEYGUARD_DONE_DRAWING:
61. handleKeyguardDoneDrawing();
62. return;
63. caseKEYGUARD_DONE_AUTHENTICATING:
64. true);
65. return;
66. case SET_HIDDEN:
67. 0);
68. break;
69. case KEYGUARD_TIMEOUT:
70. synchronized(KeyguardViewMediator.this) {
71. doKeyguardLocked();
72. }
73. break;
74. }
75. }
76. };
77. private void adjustStatusBarLocked() {
78. //控制是否能在锁屏界面下拉状态栏。
79. }
80. }
5.KeyguardViewManager.java
如果说mediator相当于总裁,那这个就是经理,而且是视图部门老大,它有一个类型为FrameLayout名叫ViewManager的内部类,用来作为keyguard的viewroot。在viewroot里添加了KeyguardHostView,我们叫它mKeyguardView。Keyguard里任何的view细节和问题都能通过它找到蛛丝马迹。
[java] view plain copy
1. /**
2. * Manages creating, showing, hiding andresetting the keyguard. Callsback
3. * via {@link KeyguardViewMediator.ViewMediatorCallback} to poke
4. * the wake lock and report that the keyguardis done, which is in turn,
5. * reported to this class by the current {@link KeyguardViewBase}.
6. */
7. public class KeyguardViewManager {
8. private final static boolean DEBUG = KeyguardViewMediator.DEBUG;
9. private static String TAG = "KeyguardViewManager";
10. public static boolean USE_UPPER_CASE = true;
11. public final static String IS_SWITCHING_USER = "is_switching_user";
12.
13. // Timeoutused for keypresses
14. static final int DIGIT_PRESS_WAKE_MILLIS = 5000;
15.
16. private final Context mContext;
17. private final ViewManager mViewManager;
18. private final KeyguardViewMediator.ViewMediatorCallbackmViewMediatorCallback;
19.
20. private WindowManager.LayoutParams mWindowLayoutParams;
21. private boolean mNeedsInput = false;
22.
23. private ViewManagerHost mKeyguardHost;
24. private KeyguardHostView mKeyguardView;
6.KeyguardHostVIew.java
这里完成keyguardView布局,实例化。分析一个自定义的viewgroup,重点需要分析的是它的构造方法和onFinishInflate()方法:
[java] view plain copy
1. public KeyguardHostView(Context context, AttributeSet attrs) {
2. super(context, attrs);
3.
4. if (DEBUG) Log.e(TAG, "KeyguardHostView()");
5.
6. mLockPatternUtils = newLockPatternUtils(context);
7.
8. // Note: This depends on KeyguardHostView getting reconstructed every timethe
9. // user switches, since mUserId will be used for the entire session.
10. // Once created, keyguard should *never* re-use this instance withanother user.
11. // In other words, mUserId should never change - hence it's marked final.
12. mUserId = mLockPatternUtils.getCurrentUser();
13.
14. DevicePolicyManager dpm =
15. (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
16. if (dpm != null) {
17. mDisabledFeatures =getDisabledFeatures(dpm);
18. null);
19. }
20.
21. mSafeModeEnabled= LockPatternUtils.isSafeModeEnabled();
22.
23. // These need to be created with the user context...
24. null;
25. try {
26. final String packageName = "system";
27. 0,
28. new UserHandle(mUserId));
29.
30. catch (NameNotFoundException e) {
31. e.printStackTrace();
32. // This should never happen, but it's better to have no widgets than tocrash.
33. userContext = context;
34. }
35.
36. new AppWidgetHost(userContext, APPWIDGET_HOST_ID, mOnClickHandler,
37. Looper.myLooper());
38.
39. mAppWidgetManager =AppWidgetManager.getInstance(userContext);
40.
41. new KeyguardSecurityModel(context);
42.
43. this);
44.
45. }
46.
47. @Override
48. protected void onFinishInflate() {
49. // Grab instances of and make any necessary changes to the main layouts.Create
50. // view state manager and wire up necessary listeners / callbacks.
51. View deleteDropTarget = findViewById(R.id.keyguard_widget_pager_delete_target);
52. mAppWidgetContainer =(KeyguardWidgetPager) findViewById(R.id.app_widget_container);
53. mAppWidgetContainer.setVisibility(VISIBLE);
54. mAppWidgetContainer.setCallbacks(mWidgetCallbacks);
55. mAppWidgetContainer.setDeleteDropTarget(deleteDropTarget);
56. 0.5f);
57.
58. mSlidingChallengeLayout =(SlidingChallengeLayout) findViewById(R.id.sliding_layout);
59. if (mSlidingChallengeLayout != null) {
60. mSlidingChallengeLayout.setOnChallengeScrolledListener(mViewStateManager);
61. }
62. mAppWidgetContainer.setViewStateManager(mViewStateManager);
63. mAppWidgetContainer.setLockPatternUtils(mLockPatternUtils);
64.
65. mMultiPaneChallengeLayout =
66. (MultiPaneChallengeLayout)findViewById(R.id.multi_pane_challenge);
67. null ? mSlidingChallengeLayout :
68. mMultiPaneChallengeLayout;
69. challenge.setOnBouncerStateChangedListener(mViewStateManager);
70. mAppWidgetContainer.setBouncerAnimationDuration(challenge.getBouncerAnimationDuration());
71. mViewStateManager.setPagedView(mAppWidgetContainer);
72. mViewStateManager.setChallengeLayout(challenge);
73. mSecurityViewContainer = (KeyguardSecurityViewFlipper)findViewById(R.id.view_flipper);
74. mKeyguardSelectorView =(KeyguardSelectorView) findViewById(R.id.keyguard_selector_view);
75. mViewStateManager.setSecurityViewContainer(mSecurityViewContainer);
76.
77. false);
78.
79. if (KeyguardUpdateMonitor.getInstance(mContext).hasBootCompleted()){
80. updateAndAddWidgets();
81. else {
82. // We can't add widgets until after boot completes because AppWidgetHostmay try
83. // to contact the providers. Do itlater.
84. new Runnable() {
85. @Override
86. public void run() {
87. updateAndAddWidgets();
88. }
89. };
90. }
91.
92. false);
93. updateSecurityViews();
94. enableUserSelectorIfNecessary();
95. }
7.KeyguardUpdateMonitor.java
说明:监听系统状态值的改变如时间、SIM卡状态、电池电量等,状态值的改变会回调监听了该状态信息的对象实例。如果只是关注功能的话只需要看hadle里面的每个消息调用的方法即可。
[java] view plain copy
1. /**
2. *Watches for updates that may be interesting to the keyguard, and provides
3. *the up to date information as well as a registration for callbacks that care
4. * tobe updated.
5. *
6. *Note: under time crunch, this has been extended to include some stuff that
7. *doesn't really belong here. see {@link#handleBatteryUpdate} where it shutdowns
8. *the device, and {@link #getFailedAttempts()}, {@link #reportFailedAttempt()}
9. *and {@link #clearFailedAttempts()}. Maybe we should rename this 'KeyguardContext'...
10. */
11. public class KeyguardUpdateMonitor {
12. private Handler mHandler;
13. private ContentObserver mContentObserver;
14. private int mRingMode;
15. private int mPhoneState;
16. ......
17.
18. /**
19. * SIM卡状态改变捕获赋值。
20. * the intent and provide a {@link SimCard.State} result.
21. */
22. private static class SimArgs {
23.
24. public final IccCard.State simState;
25.
26. private SimArgs(Intent intent) {
27. if(!TelephonyIntents.ACTION_SIM_STATE_CHANGED.equals(intent.getAction())) {
28. throw newIllegalArgumentException("only handles intentACTION_SIM_STATE_CHANGED");
29. }
30. String stateExtra = intent.getStringExtra(IccCard.INTENT_KEY_ICC_STATE);
31. if (IccCard.INTENT_VALUE_ICC_ABSENT.equals(stateExtra)) {
32. final String absentReason =intent
33. .getStringExtra(IccCard.INTENT_KEY_LOCKED_REASON);
34.
35. if(IccCard.INTENT_VALUE_ABSENT_ON_PERM_DISABLED.equals(
36. absentReason)) {
37. this.simState =IccCard.State.PERM_DISABLED;
38. else {
39. this.simState =IccCard.State.ABSENT;
40. }
41. else if (IccCard.INTENT_VALUE_ICC_READY.equals(stateExtra)) {
42. this.simState =IccCard.State.READY;
43. else if (IccCard.INTENT_VALUE_ICC_LOCKED.equals(stateExtra)) {
44. final String lockedReason =intent
45. .getStringExtra(IccCard.INTENT_KEY_LOCKED_REASON);
46. if (IccCard.INTENT_VALUE_LOCKED_ON_PIN.equals(lockedReason)){
47. this.simState =IccCard.State.PIN_REQUIRED;
48. else if(IccCard.INTENT_VALUE_LOCKED_ON_PUK.equals(lockedReason)) {
49. this.simState = IccCard.State.PUK_REQUIRED;
50. else {
51. this.simState =IccCard.State.UNKNOWN;
52. }
53. else if (IccCard.INTENT_VALUE_LOCKED_NETWORK.equals(stateExtra)) {
54. this.simState =IccCard.State.NETWORK_LOCKED;
55. else {
56. this.simState =IccCard.State.UNKNOWN;
57. }
58. }
59.
60. public String toString() {
61. return simState.toString();
62. }
63. }
64.
65. public KeyguardUpdateMonitor(Context context) {
66. mContext = context;
67.
68. new Handler() {
69. @Override
70. public void handleMessage(Message msg) {
71. switch (msg.what) {
72. case MSG_TIME_UPDATE:
73. handleTimeUpdate();
74. break;
75. case MSG_BATTERY_UPDATE:
76. handleBatteryUpdate(msg.arg1, msg.arg2);
77. break;
78. caseMSG_CARRIER_INFO_UPDATE:
79. handleCarrierInfoUpdate();
80. break;
81. case MSG_SIM_STATE_CHANGE:
82. handleSimStateChange((SimArgs) msg.obj);
83. break;
84. caseMSG_RINGER_MODE_CHANGED:
85. handleRingerModeChange(msg.arg1);
86. break;
87. caseMSG_PHONE_STATE_CHANGED:
88. handlePhoneStateChanged((String)msg.obj);
89. break;
90. caseMSG_CLOCK_VISIBILITY_CHANGED:
91. handleClockVisibilityChanged();
92. break;
93. caseMSG_DEVICE_PROVISIONED:
94. handleDeviceProvisioned();
95. break;
96. }
97. }
98. };