Android10.0 人脸解锁(下)

简介: Android10.0 人脸解锁

startListeningForFace()


// KeyguardUpdateMonitor.java
    private void startListeningForFace() {
        if (mFaceRunningState == BIOMETRIC_STATE_CANCELLING) {
            setFaceRunningState(BIOMETRIC_STATE_CANCELLING_RESTARTING);
            return;
        }
        if (DEBUG) Log.v(TAG, "startListeningForFace()");
        int userId = getCurrentUser();
        if (isUnlockWithFacePossible(userId)) {
            if (mFaceCancelSignal != null) {
                mFaceCancelSignal.cancel();
            }
            mFaceCancelSignal = new CancellationSignal();
            /*重点关注*/
            mFaceManager.authenticate(null, mFaceCancelSignal, 0,
                    mFaceAuthenticationCallback, null, userId);
            setFaceRunningState(BIOMETRIC_STATE_RUNNING);
        }
    }

FaceManager#authenticate()


// frameworks/base/core/java/android/hardware/face/FaceManager.java
    public void authenticate(@Nullable CryptoObject crypto, @Nullable CancellationSignal cancel,
            int flags, @NonNull AuthenticationCallback callback, @Nullable Handler handler,
            int userId) {
        if (callback == null) {
            throw new IllegalArgumentException("Must supply an authentication callback");
        }
        if(mPendingFaceAuth != null) {
            Log.w(TAG, "authentication too frequent");
        }
        if(mAuthenticationCallback != null) {
            mPendingFaceAuth = new PendingFaceAuth(crypto, cancel, flags, callback, handler, userId);
            Log.w(TAG, "pengding face auth");
            return;
        } else {
            /*重点关注*/
            authenticateInternel(crypto, cancel, flags, callback, handler, userId);
        }
    }
    void authenticateInternel(CryptoObject crypto, CancellationSignal cancel,
            int flags, AuthenticationCallback callback, Handler handler, int userId) {
        if (cancel != null) {
            if (cancel.isCanceled()) {
                Log.w(TAG, "authentication already canceled");
                return;
            } else {
                cancel.setOnCancelListener(new OnAuthenticationCancelListener(crypto));
            }
        }
        //mSurface = null;
        //onFaceidStarted();
        if (mService != null) {
            try {
                useHandler(handler);
                mAuthenticationCallback = callback;
                mCryptoObject = crypto;
                long sessionId = crypto != null ? crypto.getOpId() : 0;
                Trace.beginSection("FaceManager#authenticate");
                /*重点关注*/    
                // 进行人脸认证  
                mService.authenticate(mToken, sessionId, userId, mServiceReceiver,
                        flags, mContext.getOpPackageName());
                /* UNISOC: Modify for bug1374210 {@ */
                if (callback != null) {
                    callback.onAuthenticationStarted();
                }
                /* @} */
            } catch (RemoteException e) {
                 // 省略部分代码......
            } finally {
                Trace.endSection();
            }
        }
    }

FaceService#authenticate()


// frameworks/base/services/core/java/com/android/server/biometrics/face/FaceService.java
        @Override // Binder call
        public void authenticate(final IBinder token, final long opId, int userId,
                final IFaceServiceReceiver receiver, final int flags,
                final String opPackageName) {
            checkPermission(USE_BIOMETRIC_INTERNAL);
            updateActiveGroup(userId, opPackageName);
            final boolean restricted = isRestricted();
            final AuthenticationClientImpl client = new FaceAuthClient(getContext(),
                    mDaemonWrapper, mHalDeviceId, token, new ServiceListenerImpl(receiver),
                    mCurrentUserId, 0 /* groupId */, opId, restricted, opPackageName,
                    0 /* cookie */, false /* requireConfirmation */);
             /*重点关注*/
            authenticateInternal(client, opId, opPackageName);
        }

BiometricServiceBase#authenticateInternal()


protected void authenticateInternal(AuthenticationClientImpl client, long opId,
            String opPackageName) {
        final int callingUid = Binder.getCallingUid();
        final int callingPid = Binder.getCallingPid();
        final int callingUserId = UserHandle.getCallingUserId();
        authenticateInternal(client, opId, opPackageName, callingUid, callingPid, callingUserId);
    }
    protected void authenticateInternal(AuthenticationClientImpl client, long opId,
            String opPackageName, int callingUid, int callingPid, int callingUserId) {
        if (!canUseBiometric(opPackageName, true /* foregroundOnly */, callingUid, callingPid,
                callingUserId)) {
            if (DEBUG) Slog.v(getTag(), "authenticate(): reject " + opPackageName);
            return;
        }
        mHandler.post(() -> {
            mMetricsLogger.histogram(getConstants().tagAuthToken(), opId != 0L ? 1 : 0);
            // Get performance stats object for this user.
            HashMap<Integer, PerformanceStats> pmap
                    = (opId == 0) ? mPerformanceMap : mCryptoPerformanceMap;
            PerformanceStats stats = pmap.get(mCurrentUserId);
            if (stats == null) {
                stats = new PerformanceStats();
                pmap.put(mCurrentUserId, stats);
            }
            mPerformanceStats = stats;
            mIsCrypto = (opId != 0);
            /*重点关注*/
            startAuthentication(client, opPackageName);
        });
    }
    private void startAuthentication(AuthenticationClientImpl client, String opPackageName) {
        if (DEBUG) Slog.v(getTag(), "startAuthentication(" + opPackageName + ")");
        int lockoutMode = getLockoutMode();
        // getLockoutMode() 判断是否锁定,会返回一个 int 值
        if (lockoutMode != AuthenticationClient.LOCKOUT_NONE) {
            Slog.v(getTag(), "In lockout mode(" + lockoutMode + ") ; disallowing authentication");
            int errorCode = lockoutMode == AuthenticationClient.LOCKOUT_TIMED ?
                    BiometricConstants.BIOMETRIC_ERROR_LOCKOUT :
                    BiometricConstants.BIOMETRIC_ERROR_LOCKOUT_PERMANENT;
            if (!client.onError(getHalDeviceId(), errorCode, 0 /* vendorCode */)) {
                Slog.w(getTag(), "Cannot send permanent lockout message to client");
            }
            return;
        }
        /*重点关注*/
        startClient(client, true /* initiatedByClient */);
        //这里将AuthenticationClient传递进去
    }    
    private void startClient(ClientMonitor newClient, boolean initiatedByClient) {
        ClientMonitor currentClient = mCurrentClient;
        if (currentClient != null) {
            if (DEBUG) Slog.v(getTag(), "request stop current client " +
                    currentClient.getOwnerString());
            if (currentClient instanceof InternalEnumerateClient
                    || currentClient instanceof InternalRemovalClient) {
                 // 省略部分代码......
            } else {
                currentClient.stop(initiatedByClient);
                mHandler.removeCallbacks(mResetClientState);
                mHandler.postDelayed(mResetClientState, CANCEL_TIMEOUT_LIMIT);
            }
            mPendingClient = newClient;
        } else if (newClient != null) {
             // 省略部分代码......
            // We are not a BiometricPrompt client, start the client immediately
            mCurrentClient = newClient;
            /*重点关注*/
            startCurrentClient(mCurrentClient.getCookie());
            //这里继续将AuthenticationClient传递进去
        }
    }
    protected void startCurrentClient(int cookie) {
         // 省略部分代码......
         /*重点关注*/
         //这里调用的是AuthenticationClient的start方法
        int status = mCurrentClient.start();
        if (status == 0) {
            notifyClientActiveCallbacks(true);
        }
      // ... ...
    }

mCurrentClient是ClientMonitor的对象,而AuthenticationClient继承了ClientMonitor类;

AuthenticationClient#start()


// 开始验证
    public int start() {
        mStarted = true;
        onStart();
        try {
            /*重点关注*/
            // 获取 DaemonWrappe 对象开始鉴权,这里如果鉴权完成会回调注册的 ClientMonito r的 onAuthenticated 接口
            //到这一步 DaemonWrappe 对象 进入等待捕获人脸信息,摄像头会给到DaemonWrappe对象人脸信息。
            // 这里对调用到 DaemonWrapper 在 FaceService 里有实现,在那里会直接调用到 HAL 层
            final int result = getDaemonWrapper().authenticate(mOpId, getGroupId());
            if (result != 0) {
                Slog.w(getLogTag(), "startAuthentication failed, result=" + result);
                mMetricsLogger.histogram(mConstants.tagAuthStartError(), result);
                onError(getHalDeviceId(), BiometricConstants.BIOMETRIC_ERROR_HW_UNAVAILABLE,
                        0 /* vendorCode */);
                return result;
            }
            if (DEBUG) Slog.w(getLogTag(), "client " + getOwnerString() + " is authenticating...");
        } catch (RemoteException e) {
            Slog.e(getLogTag(), "startAuthentication failed", e);
            return ERROR_ESRCH;
        }
        return 0; // success
    }

start方法会调用faced,调用底层的人脸库,底层库返回结果后会调用onAuthenticated来反馈结果给receiver,在往上层反馈。

补充:IExtBiometricsFace.hal 这个接口在 ExtBiometricsFace.cpp中实现。


// FaceService.java
    @Override
    public void onStart() {
        super.onStart();
        // 在初始化后会建立和HAL层的通信,即连接到 FaceService,
        //并通过getFaceDaemon()拿到用于通信的 IExtBiometricsFace对象(binder)
        publishBinderService(Context.FACE_SERVICE, new FaceServiceWrapper());
        SystemServerInitThreadPool.submit(() -> mHandler.post(this::getFaceDaemon),
                TAG + ".onStart");
    }


屏幕解锁(结果回调、移除锁)

底层库回调onAuthenticated堆栈:


09-13 16:33:49.998  1017  1017 D yexiao  : yexiao:FaceService.java ServiceListenerImpl onAuthenticationSucceeded()
09-13 16:33:49.998  1017  1017 D yexiao  : java.lang.Throwable
09-13 16:33:49.998  1017  1017 D yexiao  :      at com.android.server.biometrics.face.FaceService$ServiceListenerImpl.onAuthenticationSucceeded(FaceService.java:918)
09-13 16:33:49.998  1017  1017 D yexiao  :      at com.android.server.biometrics.AuthenticationClient.onAuthenticated(AuthenticationClient.java:235)
09-13 16:33:49.998  1017  1017 D yexiao  :      at com.android.server.biometrics.face.FaceService$FaceAuthClient.onAuthenticated(FaceService.java:297)
09-13 16:33:49.998  1017  1017 D yexiao  :      at com.android.server.biometrics.BiometricServiceBase.handleAuthenticated(BiometricServiceBase.java:729)
09-13 16:33:49.998  1017  1017 D yexiao  :      at com.android.server.biometrics.face.FaceService.access$11801(FaceService.java:110)
09-13 16:33:49.998  1017  1017 D yexiao  :      at com.android.server.biometrics.face.FaceService$1.lambda$onAuthenticated$2$FaceService$1(FaceService.java:1040)
09-13 16:33:49.998  1017  1017 D yexiao  :      at com.android.server.biometrics.face.-$$Lambda$FaceService$1$GcU4ZG1fdDLhKvSxuMwfPargEnI.run(Unknown Source:8)
09-13 16:33:49.998  1017  1017 D yexiao  :      at android.os.Handler.handleCallback(Handler.java:938)
09-13 16:33:49.998  1017  1017 D yexiao  :      at android.os.Handler.dispatchMessage(Handler.java:99)
09-13 16:33:49.998  1017  1017 D yexiao  :      at android.os.Looper.loop(Looper.java:223)
09-13 16:33:49.998  1017  1017 D yexiao  :      at com.android.server.SystemServer.run(SystemServer.java:647)
09-13 16:33:49.998  1017  1017 D yexiao  :      at com.android.server.SystemServer.main(SystemServer.java:431)
09-13 16:33:49.998  1017  1017 D yexiao  :      at java.lang.reflect.Method.invoke(Native Method)
09-13 16:33:49.998  1017  1017 D yexiao  :      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:603)
09-13 16:33:49.998  1017  1017 D yexiao  :      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:925)

根据前面的讲的 底层 Face HIDL 可以知道 IExtBiometricsFaceClientCallback 是回调人脸识别结果的。onAuthenticated()是当一张人脸被成功认证时被回调。


// FaceService.java
    /**
     * Receives callbacks from the HAL.
     */
    private IExtBiometricsFaceClientCallback mDaemonCallback =
            new IExtBiometricsFaceClientCallback.Stub() {
         // 省略部分代码 ......
        @Override
        public void onAuthenticated(final long deviceId, final int faceId, final int userId,
                ArrayList<Byte> token) {
            mHandler.post(() -> {
                final Face face = new Face("", faceId, deviceId);
                final boolean authenticated = faceId != 0;
                /*重点在这里*/
                FaceService.super.handleAuthenticated(authenticated, face, token);
            });
        }
         // 省略部分代码 ......
    };

通过上面 FaceService.super.handleAuthenticated(authenticated, face, token) 的调用。将会调用到:

BiometricServiceBase#handleAuthenticated()


// BiometricServiceBase.java
    protected void handleAuthenticated(boolean authenticated,
            BiometricAuthenticator.Identifier identifier, ArrayList<Byte> token) {
        Log.d("yexiao","yexiao:AuthenticationClient.java ----------------2 ");
        ClientMonitor client = mCurrentClient;
        // 重点在后半句判断,通过前面的分析可以知道 client 其实是 FaceAuthClient 的对象
        if (client != null && client.onAuthenticated(identifier, authenticated, token)) {
            removeClient(client);
        }
        if (authenticated) {
            mPerformanceStats.accept++;
        } else {
            mPerformanceStats.reject++;
        }
    }

通过前面的分析可以知道 client 其实是 FaceAuthClient 的对象,在FaceService.java 的内部类FaceServiceWrapper的authenticate()方法进行实例化传过去的。反正最终将会回调到FaceService.java 的内部类FaceAuthClient的onAuthenticated()方法

        @Override
        public boolean onAuthenticated(BiometricAuthenticator.Identifier identifier,
                boolean authenticated, ArrayList<Byte> token) {
            Log.d("yexiao","yexiao:FaceAuthClient onAuthenticated ",new Throwable());
            // 重点关注super
            final boolean result = super.onAuthenticated(identifier, authenticated, token);
            mUsageStats.addEvent(new AuthenticationEvent(
                    getStartTimeMs(),
                    System.currentTimeMillis() - getStartTimeMs() /* latency */,
                    authenticated,
                    0 /* error */,
                    0 /* vendorError */,
                    getTargetUserId()));
            // For face, the authentication lifecycle ends either when
            // 1) Authenticated == true
            // 2) Error occurred
            // 3) Authenticated == false
            // Fingerprint currently does not end when the third condition is met which is a bug,
            // but let's leave it as-is for now.
            return result || !authenticated;
        }


这里的super将会调到父类AuthenticationClient中的onAuthenticated()。

AuthenticationClient#onAuthenticated()

// AuthenticationClient.java
    public boolean onAuthenticated(BiometricAuthenticator.Identifier identifier,
            boolean authenticated, ArrayList<Byte> token) {
        super.logOnAuthenticated(getContext(), authenticated, mRequireConfirmation,
                getTargetUserId(), isBiometricPrompt());
          // 省略部分代码 ......
        try {
            if (DEBUG) Slog.v(getLogTag(), "onAuthenticated(" + authenticated + ")"
                    + ", ID:" + identifier.getBiometricId()
                    + ", Owner: " + getOwnerString()
                    + ", isBP: " + isBiometricPrompt()
                    + ", listener: " + listener
                    + ", requireConfirmation: " + mRequireConfirmation
                    + ", user: " + getTargetUserId());
            if (authenticated) { 
              // 省略部分代码 ......
                    try {
                        // Explicitly have if/else here to make it super obvious in case the code is
                        // touched in the future.
                        if (!getIsRestricted()) {
                            /*重点关注*/ 
                            // getIsRestricted() 获取有没有权限登录,说白了就是验证是否成功
                            listener.onAuthenticationSucceeded(
                                    getHalDeviceId(), identifier, getTargetUserId());
                        } else {
                            listener.onAuthenticationSucceeded(
                                    getHalDeviceId(), null, getTargetUserId());
                        }
                    } catch (RemoteException e) {
                        Slog.e(getLogTag(), "Remote exception", e);
                    }
                } else {
                    // Client not listening
                    Slog.w(getLogTag(), "Client not listening");
                    result = true;
                }
            } else {
             // 省略部分代码 ......
            }
        } catch (RemoteException e) {
            Slog.e(getLogTag(), "Remote exception", e);
            result = true;
        }
        return result;
    }

这里的 listener 其实是 BiometricServiceBase.ServiceListener 接口的回调,BiometricServiceBase的内部类BiometricServiceListener也实现了该接口,但是没有实现onAuthenticationSucceeded() 方法,而该ServiceListener 接口在FaceService中的内部类ServiceListenerImpl 也有实现,并且实现了onAuthenticationSucceeded() 方法。所以将会回调到FaceService内部类的 ServiceListenerImpl#onAuthenticationSucceeded()。

ServiceListenerImpl#onAuthenticationSucceeded()

/**
     * 从 ClientMonitor 实现接收回调。结果被转发到 FaceManager
     */
    private class ServiceListenerImpl implements ServiceListener {
        private IFaceServiceReceiver mFaceServiceReceiver;
        public ServiceListenerImpl(IFaceServiceReceiver receiver) {
            mFaceServiceReceiver = receiver;
        }
         // 省略部分代码 ......
        @Override
        public void onAuthenticationSucceeded(long deviceId,
                BiometricAuthenticator.Identifier biometric, int userId)
                throws RemoteException {
            if (mFaceServiceReceiver != null) {
                if (biometric == null || biometric instanceof Face) {
                    // 重点关注这里
                    mFaceServiceReceiver.onAuthenticationSucceeded(deviceId, (Face) biometric,
                            userId, isStrongBiometric());
                } else {
                    Slog.e(TAG, "onAuthenticationSucceeded received non-face biometric");
                }
            }
        }
         // 省略部分代码 ......
    }

ServiceListenerImpl  这个类是负责将回调结果,转发到 FaceManager 中的。通过 IFaceServiceReceiver 的对象,回调 FaceManager 中的 onAuthenticationSucceeded() 方法。

FaceManager#onAuthenticationSucceeded()

// FaceManager.java
    private IFaceServiceReceiver mServiceReceiver = new IFaceServiceReceiver.Stub() {
         // 省略部分代码 ......
        @Override // binder call
        public void onAuthenticationSucceeded(long deviceId, Face face, int userId,
                boolean isStrongBiometric) {
            mHandler.obtainMessage(MSG_AUTHENTICATION_SUCCEEDED, userId, isStrongBiometric ? 1 : 0,
                    face).sendToTarget();
            //onFaceidStopped();
        }
         // 省略部分代码 ......
    };

在这里通过 mHandler 发送了 MSG_AUTHENTICATION_SUCCEEDED 消息,在 handleMessage 中将会执行 sendAuthenticatedSucceeded() 方法。

// FaceManager.java
    private void sendAuthenticatedSucceeded(Face face, int userId, boolean isStrongBiometric) {
        if (mAuthenticationCallback != null) {
            final AuthenticationResult result =
                    new AuthenticationResult(mCryptoObject, face, userId, isStrongBiometric);
            // 主要关注这里
            mAuthenticationCallback.onAuthenticationSucceeded(result); 
            mAuthenticationCallback = null;
            if(mPendingFaceAuth != null) {
                authenticateInternel(mPendingFaceAuth.mCrypto, mPendingFaceAuth.mCancel, mPendingFaceAuth.mFlags, mPendingFaceAuth.mCallback, mPendingFaceAuth.mHandler, mPendingFaceAuth.mUserId);
                mPendingFaceAuth = null;
            }
        }
    }

在 sendAuthenticatedSucceeded() 方法中将会执行 BiometricAuthenticator.AuthenticationCallback 的接口的回调,将会把结果回调到 KeyguardUpdateMonitor 中FaceManager.AuthenticationCallback 的onAuthenticationSucceeded() 方法。

FaceManager.AuthenticationCallback#onAuthenticationSucceeded()

可以看一个堆栈图:

09-13 16:33:50.024  1414  1414 D yexiao  : java.lang.Throwable
09-13 16:33:50.024  1414  1414 D yexiao  :      at com.android.keyguard.KeyguardUpdateMonitor$15.onAuthenticationSucceeded(KeyguardUpdateMonitor.java:1427)
09-13 16:33:50.024  1414  1414 D yexiao  :      at android.hardware.face.FaceManager.sendAuthenticatedSucceeded(FaceManager.java:1212)
09-13 16:33:50.024  1414  1414 D yexiao  :      at android.hardware.face.FaceManager.access$1300(FaceManager.java:63)
09-13 16:33:50.024  1414  1414 D yexiao  :      at android.hardware.face.FaceManager$MyHandler.handleMessage(FaceManager.java:1120)
09-13 16:33:50.024  1414  1414 D yexiao  :      at android.os.Handler.dispatchMessage(Handler.java:106)
09-13 16:33:50.024  1414  1414 D yexiao  :      at android.os.Looper.loop(Looper.java:223)
09-13 16:33:50.024  1414  1414 D yexiao  :      at android.app.ActivityThread.main(ActivityThread.java:7945)
09-13 16:33:50.024  1414  1414 D yexiao  :      at java.lang.reflect.Method.invoke(Native Method)
09-13 16:33:50.024  1414  1414 D yexiao  :      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:603)
09-13 16:33:50.024  1414  1414 D yexiao  :      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

// KeyguardUpdateMonitor.java 
    @VisibleForTesting
    FaceManager.AuthenticationCallback mFaceAuthenticationCallback
            = new FaceManager.AuthenticationCallback() {
        @Override
        public void onAuthenticationFailed() {
            // 身份验证失败
            handleFaceAuthFailed();
        }
        /* UNISOC: Modify for bug1374210 {@ */
        @Override
        public void onAuthenticationStarted() {
            handleFaceAuthStarted();
        }
        /* @} */
        @Override
        public void onAuthenticationSucceeded(FaceManager.AuthenticationResult result) {
            Log.d("yexiao","yexiao:onAuthenticationSucceeded",new Throwable());
            Trace.beginSection("KeyguardUpdateMonitor#onAuthenticationSucceeded");
            // 重点关注
            handleFaceAuthenticated(result.getUserId(), result.isStrongBiometric());
            Trace.endSection();
        }
        @Override
        public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
            handleFaceHelp(helpMsgId, helpString.toString());
        }
        @Override
        public void onAuthenticationError(int errMsgId, CharSequence errString) {
            // 人脸处理操作已取消或未识别到
            handleFaceError(errMsgId, errString.toString());
        }
        @Override
        public void onAuthenticationAcquired(int acquireInfo) {
            handleFaceAcquired(acquireInfo);
        }
    };

KeyguardUpdateMonitor#handleFaceAuthenticated()

// KeyguardUpdateMonitor.java 
    private void handleFaceAuthenticated(int authUserId) {
        Trace.beginSection("KeyGuardUpdateMonitor#handlerFaceAuthenticated");
        try {
            final int userId;
            try {
                userId = ActivityManager.getService().getCurrentUser().id;
            } catch (RemoteException e) {
                Log.e(TAG, "Failed to get current user id: ", e);
                return;
            }
            if (userId != authUserId) {
                Log.d(TAG, "Face authenticated for wrong user: " + authUserId);
                return;
            }
            if (isFaceDisabled(userId)) {
                Log.d(TAG, "Face authentication disabled by DPM for userId: " + userId);
                return;
            }
            /*重点关注*/
            onFaceAuthenticated(userId);
        } finally {
            setFaceRunningState(BIOMETRIC_STATE_STOPPED);
        }
        Trace.endSection();
    }

handleFaceAuthenticated#onFaceAuthenticated

// KeyguardUpdateMonitor.java
    protected void onFaceAuthenticated(int userId) {
        Trace.beginSection("KeyGuardUpdateMonitor#onFaceAuthenticated");
        mUserFaceAuthenticated.put(userId, true);
        // Update/refresh trust state only if user can skip bouncer
        if (getUserCanSkipBouncer(userId)) {
            mTrustManager.unlockedByBiometricForUser(userId, BiometricSourceType.FACE);
        }
        // Don't send cancel if authentication succeeds
        mFaceCancelSignal = null;
        for (int i = 0; i < mCallbacks.size(); i++) {
            /*重点关注*/
            KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
            if (cb != null) {
                /*重点关注*/
                cb.onBiometricAuthenticated(userId,
                        BiometricSourceType.FACE);
            }
        }
       mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_BIOMETRIC_AUTHENTICATION_CONTINUE),
                BIOMETRIC_CONTINUE_DELAY_MS);
        // Only authenticate face once when assistant is visible
        mAssistantVisible = false;
        Trace.endSection();
    }

这里开始调用接口将解锁成功消息层层传递直至keyguard解锁,与指纹解锁逻辑一致

可以看到在 onFaceAuthenticated(userId) 方法中调用了 KeyguardUpdateMonitorCallback 这个抽象类的 onBiometricAuthenticated() 抽象方法,而 BiometricUnlockController extends KeyguardUpdateMonitorCallback,并且注册了回调 mUpdateMonitor.registerCallback(this)。

BiometricUnlockController #onBiometricAuthenticated()

// BiometricUnlockController.java
    @Override
    public void onBiometricAuthenticated(int userId, BiometricSourceType biometricSourceType,
            boolean isStrongBiometric) {
        // 省略部分代码......
        if (unlockAllowed) {
            mKeyguardViewMediator.userActivity();
            /*重点关注*/
            // 开始唤醒和解锁
            startWakeAndUnlock(biometricSourceType, isStrongBiometric);
        } else {
            Log.d(TAG, "onBiometricAuthenticated aborted by bypass controller");
        }
    }

BiometricUnlockController#startWakeAndUnlock

// BiometricUnlockController.java
    public void startWakeAndUnlock(int mode) {
        // 省略部分代码......
        Runnable wakeUp = ()-> {
            if (!wasDeviceInteractive) {
                if (DEBUG_BIO_WAKELOCK) {
                    Log.i(TAG, "bio wakelock: Authenticated, waking up...");
                }
                mPowerManager.wakeUp(SystemClock.uptimeMillis(), PowerManager.WAKE_REASON_GESTURE,
                        "android.policy:BIOMETRIC");
            }
            if (delayWakeUp) {
               /*重点关注*/
                mKeyguardViewMediator.onWakeAndUnlocking();
            }
            Trace.beginSection("release wake-and-unlock");
            releaseBiometricWakeLock();
            Trace.endSection();
        };
        // 省略部分代码......
        mStatusBar.notifyBiometricAuthModeChanged();
        Trace.endSection();
    }

KeyguardViewMediator#onWakeAndUnlocking()

// KeyguardViewMediator.java
    public void onWakeAndUnlocking() {
        Trace.beginSection("KeyguardViewMediator#onWakeAndUnlocking");
        mWakeAndUnlocking = true;
        /*重点关注*/
        keyguardDone();
        Trace.endSection();
    }

KeyguardViewMediator#keyguardDone()

// KeyguardViewMediator.java
    public void keyguardDone() {
        Trace.beginSection("KeyguardViewMediator#keyguardDone");
        if (DEBUG) Log.d(TAG, "keyguardDone()");
        userActivity();
        EventLog.writeEvent(70000, 2);
        /*重点关注*/
        Message msg = mHandler.obtainMessage(KEYGUARD_DONE);
        mHandler.sendMessage(msg);
        Trace.endSection();
    }

keyguardDone()该方法发送了一条 KEYGUARD_DONE 消息,在 handleMessage 中将会执行 handleKeyguardDone() 方法。

KeyguardViewMediator#handleKeyguardDone()

// KeyguardViewMediator.java
    private void handleKeyguardDone() {
        Trace.beginSection("KeyguardViewMediator#handleKeyguardDone");
        final int currentUser = KeyguardUpdateMonitor.getCurrentUser();
        // 省略部分代码......
        /*
         * 重点关注
         * 处理隐藏
        **/
        handleHide();
        Trace.endSection();
    }

KeyguardViewMediator# handleHide()

// KeyguardViewMediator.java
    private void handleHide() {
        Trace.beginSection("KeyguardViewMediator#handleHide");
        // It's possible that the device was unlocked in a dream state. It's time to wake up.
        if (mAodShowing) {
            PowerManager pm = mContext.getSystemService(PowerManager.class);
            pm.wakeUp(SystemClock.uptimeMillis(), PowerManager.WAKE_REASON_GESTURE,
                    "com.android.systemui:BOUNCER_DOZING");
        }
        synchronized (KeyguardViewMediator.this) {
            if (DEBUG) Log.d(TAG, "handleHide");
            if (mustNotUnlockCurrentUser()) {
                if (DEBUG) Log.d(TAG, "Split system user, quit unlocking.");
                return;
            }
            mHiding = true;
            if (mShowing && !mOccluded) {
                mKeyguardGoingAwayRunnable.run();
            } else {
                /*重点关注*/
                // 处理开始键盘保护退出动画
                handleStartKeyguardExitAnimation(
                        SystemClock.uptimeMillis() + mHideAnimation.getStartOffset(),
                        mHideAnimation.getDuration());
            }
        }
        Trace.endSection();
    }

KeyguardViewMediator#handleStartKeyguardExitAnimation()

// KeyguardViewMediator.java
    private void handleStartKeyguardExitAnimation(long startTime, long fadeoutDuration) {
        Trace.beginSection("KeyguardViewMediator#handleStartKeyguardExitAnimation");
        // 省略部分代码......
            mWakeAndUnlocking = false;
            setShowingLocked(false, mAodShowing);
            mDismissCallbackRegistry.notifyDismissSucceeded();
            /*重点关注*/
            mStatusBarKeyguardViewManager.hide(startTime, fadeoutDuration);
            resetKeyguardDonePendingLocked();
            mHideAnimationRun = false;
            adjustStatusBarLocked();
            sendUserPresentBroadcast();
        }
        Trace.endSection();
    }

下面就不详细分析了,将会按如下顺序执行:StatusBarKeyguardViewManager#hide()→StatusBarKeyguardViewManager#hideBouncer()→KeyguardBouncer#hide()→KeyguardBouncer#mRemoveViewRunnable→KeyguardBouncer#removeView()。

至此锁屏界面移除的逻辑基本clear

相关文章
|
3月前
|
API 开发工具 Android开发
视觉智能开放平台产品使用合集之人脸活体检测能力是否支持Android端或者iOS端直接调用
视觉智能开放平台是指提供一系列基于视觉识别技术的API和服务的平台,这些服务通常包括图像识别、人脸识别、物体检测、文字识别、场景理解等。企业或开发者可以通过调用这些API,快速将视觉智能功能集成到自己的应用或服务中,而无需从零开始研发相关算法和技术。以下是一些常见的视觉智能开放平台产品及其应用场景的概览。
|
安全 算法 Android开发
Android10.0 人脸解锁(上)
Android10.0 人脸解锁(上)
Android10.0 人脸解锁(上)
|
存储 传感器 安全
Android11.0 增加人脸解锁功能
Android11.0 增加人脸解锁功能
946 0
|
安全 Android开发 数据安全/隐私保护
Android支持Smart Lock 人脸解锁
Android支持Smart Lock 人脸解锁
303 0
|
算法 数据处理 开发工具
|
测试技术 API 数据安全/隐私保护
Android——实现人脸支付
功能实现 人脸支付 API初始化 人脸特征提取 返回支付结果 密码框输入支付 自定义密码输入框控件 初始化控件 密码匹配 尾言 效果展
369 0
|
算法 Java Android开发
Android 中使用 dlib+opencv 实现动态人脸检测
1 概述 完成 Android 相机预览功能以后,在此基础上我使用 dlib 与 opencv 库做了一个关于人脸检测的 demo。
1850 0
|
前端开发 Android开发 计算机视觉
Android FeceDetector(人脸识别)
1. FectDetector 人脸的检测方法是用双眼来检测人脸的位置,也就是说无法检测到嘴、侧脸等,双眼必须同时可见,并且眼镜会影响检测的效果。实际上,FaceDetector检测到的并不是人的全脸,而只是双眼。
1446 0
|
机器学习/深度学习 前端开发 API
Android 开发者如何通过运动视觉 API 进行机器学习 - 第一部 - 人脸检测
本文讲的是Android 开发者如何通过运动视觉 API 进行机器学习 - 第一部 - 人脸检测,在计算机科学中,机器学习是一个非常有意思的领域,它已经在我的最想学习的愿望清单中驻留已久。因为有太多来自于RxJava, Testing, Android N, Android Studio 以及其他 Android 相关的技术更新,所以我都每能花时间来学习这个。
1888 0
|
存储 前端开发 API