切换到新活动时指纹停止工作

时间:2018-08-01 16:19:15

标签: java android android-activity android-fingerprint-api

我以 googlesamples / android-FingerprintDialog 存储库为例实现了指纹代码。 Link to repo

该代码工作正常,除了特定的情况。我有这个登录屏幕,在打开应用程序后,听众立即被激活,并且正在等待手指前进到该应用程序(如示例中所示,没有弹出窗口),但是如果手指失败了5次,则监听器会旋转关闭(使用FingerprintUiHelper.java中的 stopListening 方法,并且应用程序指纹选项已禁用,您需要输入密码才能继续操作,但是登录后可以重新启用指纹选项通过在新活动中再次确认指纹进行确认。

最后一部分是所有内容分开的地方,在这个新活动中,我再次调用 startListening ,但是传感器/侦听器将无法工作。

private void init() {
    // KeyStore init
    try {
        mKeyStore = KeyStore.getInstance("AndroidKeyStore");
    } catch (KeyStoreException e) {
        initErrorPublishSubject.onNext(true);
    }

    // KeyGenerator init
    try {
        mKeyGenerator = KeyGenerator
                .getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        initErrorPublishSubject.onNext(true);
    }

    // Cipher init
    try {
        defaultCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
                + KeyProperties.BLOCK_MODE_CBC + "/"
                + KeyProperties.ENCRYPTION_PADDING_PKCS7);
        cipherNotInvalidated = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
                + KeyProperties.BLOCK_MODE_CBC + "/"
                + KeyProperties.ENCRYPTION_PADDING_PKCS7);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        initErrorPublishSubject.onNext(true);
    }

    // Managers init
    KeyguardManager mKeyguardManager = context.getSystemService(KeyguardManager.class);
    mFingerprintManager = context.getSystemService(FingerprintManager.class);

    if (mKeyguardManager != null && !mKeyguardManager.isKeyguardSecure()) {
        // Show a message that the user hasn't set up a fingerprint or lock screen.
        initErrorPublishSubject.onNext(true);
    }

    // Now the protection level of USE_FINGERPRINT permission is normal instead of dangerous.
    // See http://developer.android.com/reference/android/Manifest.permission.html#USE_FINGERPRINT
    // The line below prevents the false positive inspection from Android Studio
    if (mFingerprintManager != null && !mFingerprintManager.hasEnrolledFingerprints()) {
        // This happens when no fingerprints are registered.
        initErrorPublishSubject.onNext(true);
    }
    createKey(DEFAULT_KEY_NAME, true);
    createKey(KEY_NAME_NOT_INVALIDATED, false);

    mFingerprintHandler = new FingerprintHandler(context, mFingerprintManager);
}

/**
 * Creates a symmetric key in the Android Key Store which can only be used after the user has
 * authenticated with fingerprint.
 *
 * @param keyName                          the name of the key to be created
 * @param invalidatedByBiometricEnrollment if {@code false} is passed, the created key will not
 *                                         be invalidated even if a new fingerprint is enrolled.
 *                                         The default value is {@code true}, so passing
 *                                         {@code true} doesn't change the behavior
 *                                         (the key will be invalidated if a new fingerprint is
 *                                         enrolled.). Note that this parameter is only valid if
 *                                         the app works on Android N developer preview.
 */
public void createKey(String keyName, boolean invalidatedByBiometricEnrollment) {
    // The enrolling flow for fingerprint. This is where you ask the user to set up fingerprint
    // for your flow. Use of keys is necessary if you need to know if the set of
    // enrolled fingerprints has changed.
    try {
        mKeyStore.load(null);
        // Set the alias of the entry in Android KeyStore where the key will appear
        // and the constrains (purposes) in the constructor of the Builder

        KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(keyName,
                KeyProperties.PURPOSE_ENCRYPT |
                        KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                // Require the user to authenticate with a fingerprint to authorize every use
                // of the key
                .setUserAuthenticationRequired(true)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7);

        // This is a workaround to avoid crashes on devices whose API level is < 24
        // because KeyGenParameterSpec.Builder#setInvalidatedByBiometricEnrollment is only
        // visible on API level +24.
        // Ideally there should be a compat library for KeyGenParameterSpec.Builder but
        // which isn't available yet.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            builder.setInvalidatedByBiometricEnrollment(invalidatedByBiometricEnrollment);
        }
        mKeyGenerator.init(builder.build());
        mKeyGenerator.generateKey();
    } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException
            | CertificateException | IOException e) {
        initErrorPublishSubject.onNext(true);
    }
}

/**
 * Initialize the {@link Cipher} instance with the created key in the
 * {@link #createKey(String, boolean)} method.
 *
 * @param keyName the key name to init the cipher
 * @return {@code true} if initialization is successful, {@code false} if the lock screen has
 * been disabled or reset after the key was generated, or if a fingerprint got enrolled after
 * the key was generated.
 */
private boolean initCipher(Cipher cipher, String keyName) {
    try {
        mKeyStore.load(null);
        SecretKey key = (SecretKey) mKeyStore.getKey(keyName, null);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return true;
    } catch (KeyPermanentlyInvalidatedException e) {
        return false;
    } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException
            | NoSuchAlgorithmException | InvalidKeyException e) {
        initErrorPublishSubject.onNext(true);
        return false;
    }
}

private void startListening(Cipher mCipher, String mKeyName) {
    if (deviceIsFingerprintCompatible(context) && initCipher(mCipher, mKeyName)) {
        mFingerprintHandler.startListening(new FingerprintManager.CryptoObject(mCipher));
    }
}

这是我的类代码声明,我将其注入需要的控制器上,我只是在下面调用此方法来启动它,这在上段代码中调用了私有方法。

public void startListening() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        startListening(cipherNotInvalidated, KEY_NAME_NOT_INVALIDATED);
    } else {
        startListening(defaultCipher, DEFAULT_KEY_NAME);
    }
}

在我的 FingerprintHandler 上,我还有其他两种方法(与原始方法相比有所简化)。

public void startListening(FingerprintManager.CryptoObject cryptoObject) {
    mCancellationSignal = new CancellationSignal();
    // The line below prevents the false positive inspection from Android Studio
    // noinspection ResourceType
    mFingerprintManager.authenticate(cryptoObject, mCancellationSignal, 0 /* flags */, this, null);
}

public void stopListening() {
    if (mCancellationSignal != null) {
        mCancellationSignal.cancel();
    }
}

您是否知道为什么在停止监听器并在新活动上启动监听器后,监听器仍无法工作?

谢谢。

0 个答案:

没有答案