android 指纹锁工具类

android sdk版本超过23以上就可以支持添加指纹识别功能,因此可以为自己的应用添加指纹锁这个概念的启动限制。高于23,少于28版本的,调用方法后如果屏幕前盖有指纹工具的话会显示指纹锁出来,高于28版本会出来指纹锁识别对话框,由系统本身提供,有回调函数支持各种事件,记录下具体的识别工具类。

import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.hardware.biometrics.BiometricPrompt;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.CancellationSignal;
import android.os.Handler;
import android.os.Message;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.text.TextUtils;
import android.util.Log;
import java.security.KeyStore;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class FingerPrintUtil {
    private Context mContext;
    private BiometricPrompt mBiometricPrompt;
    private BiometricPrompt.AuthenticationCallback mAuthenticationCallback;

    public FingerPrintUtil(Context context) {
        mContext = context;
    }

    private FingerprintManager fingerprintManager;

    public int isSupportFingerPrint(boolean isNeedShowToast) {
        if (Build.VERSION.SDK_INT >= 23) {
            try {
                KeyguardManager keyguardManager = mContext.getSystemService(KeyguardManager.class);
                fingerprintManager = mContext.getSystemService(FingerprintManager.class);
                if (fingerprintManager != null) {
                    if (!fingerprintManager.isHardwareDetected()) {
                        return -1;
                    } else if (keyguardManager != null) {
                        if (!keyguardManager.isKeyguardSecure()) {
                            if (isNeedShowToast) {
                                CustomToast.showWarningToast(mContext, “您还未设置锁屏,请先设置锁屏并添加一个指纹”));
                            }
                            return 0;
                        } else if (!fingerprintManager.hasEnrolledFingerprints()) {
                            if (isNeedShowToast) {
                                CustomToast.showWarningToast(mContext, “您至少需要在系统设置中添加一个指纹”));
                            }
                            return 0;
                        }
                    }
                    if (Build.VERSION.SDK_INT < 28) {
                        initKey();
                        initCipher();
                    } else {
                        try {
                            mCancellationSignal = new CancellationSignal();
                            mBiometricPrompt = new BiometricPrompt.Builder(mContext)
                                    .setTitle(“验证指纹密码”)
                                    .setDescription(“请确认您的指纹”))
                                    .setNegativeButton(“取消”, mContext.getMainExecutor(), new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (mFingerPrintCheckListener != null) {
                                                mFingerPrintCheckListener.checkCancel();
                                            }
                                        }
                                    }).build();
                            mAuthenticationCallback = new BiometricPrompt.AuthenticationCallback() {
                                @Override
                                public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {
                                    super.onAuthenticationSucceeded(result);
                                    if (!isFinishing()) {
                                        CustomToast.showSuccessedToast(mContext, mContext.getResources().getString(R.string.check_success));
                                        if (mFingerPrintCheckListener != null) {
                                            mFingerPrintCheckListener.checkSuccess();
                                        }
                                    }
                                }

                                @Override
                                public void onAuthenticationError(int errorCode, CharSequence errString) {
                                    super.onAuthenticationError(errorCode, errString);
                                    String str = errString + "";
                                    if (errorCode == BiometricPrompt.BIOMETRIC_ERROR_CANCELED || errorCode == BiometricPrompt.BIOMETRIC_ERROR_USER_CANCELED) {
                                        if (mFingerPrintCheckListener != null) {
                                            mFingerPrintCheckListener.checkCancel();
                                        }
                                    } else {
                                        if (mFingerPrintCheckListener != null) {
                                            mFingerPrintCheckListener.checkFail(str);
                                        }
                                    }
                                }
                            };
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    return 1;
                }
            } catch (Exception e) {
                e.printStackTrace();
                fingerprintManager = null;
            }
        }
        return -1;
    }

    // 初始化密钥
    private void initCipher() {
        try {
            SecretKey key = (SecretKey) keyStore.getKey(DEFAULT_KEY_NAME, null);
            cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
                    + KeyProperties.BLOCK_MODE_CBC + "/"
                    + KeyProperties.ENCRYPTION_PADDING_PKCS7);
            cipher.init(Cipher.ENCRYPT_MODE, key);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

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

    private KeyStore keyStore;
    private Cipher cipher;
    private static final String DEFAULT_KEY_NAME = "default_key";
    private CancellationSignal mCancellationSignal;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    // 初始化密钥库
    private void initKey() {
        if (Build.VERSION.SDK_INT >= 23) {
            try {
                keyStore = KeyStore.getInstance("AndroidKeyStore");
                keyStore.load(null);
                KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
                KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(DEFAULT_KEY_NAME,
                        KeyProperties.PURPOSE_ENCRYPT |
                                KeyProperties.PURPOSE_DECRYPT)
                        .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                        .setUserAuthenticationRequired(true)
                        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7);
                keyGenerator.init(builder.build());
                keyGenerator.generateKey();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void startFingerPrintCheck() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (Build.VERSION.SDK_INT < 28) {
                if (fingerprintManager != null) {
                    mCancellationSignal = new CancellationSignal();
                    fingerprintManager.authenticate(new FingerprintManager.CryptoObject(cipher), mCancellationSignal, 0, new FingerprintManager.AuthenticationCallback() {
                        @Override
                        public void onAuthenticationError(int errorCode, CharSequence errString) {
                            super.onAuthenticationError(errorCode, errString);
                            if (!isFinishing() && !TextUtils.isEmpty(errString)) {
                                CustomToast.showWarningToast(mContext, errString.toString());
                            }
                        }

                        @Override
                        public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
                            super.onAuthenticationHelp(helpCode, helpString);
                            if (!isFinishing() && !TextUtils.isEmpty(helpString)) {
                                CustomToast.showNotimgToast(mContext, helpString.toString());
                            }
                        }

                        @Override
                        public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
                            super.onAuthenticationSucceeded(result);
                            if (!isFinishing()) {
                                CustomToast.showSuccessedToast(mContext, mContext.getResources().getString(R.string.check_success));
                                if (mFingerPrintCheckListener != null) {
                                    mFingerPrintCheckListener.checkSuccess();
                                }
                            }
                        }

                        @Override
                        public void onAuthenticationFailed() {
                            super.onAuthenticationFailed();
                            if (!isFinishing()) {
                                CustomToast.showFailedToast(mContext, mContext.getResources().getString(R.string.check_fail));
                            }
                        }
                    }, handler);
                }
            } else {
                if (mBiometricPrompt != null) {
                    mBiometricPrompt.authenticate(mCancellationSignal, mContext.getMainExecutor(), mAuthenticationCallback);
                }
            }
        }
    }

    public boolean isFinishing() {
        if (mContext != null && mContext instanceof Activity) {
            return ((Activity) mContext).isFinishing();
        }
        return true;
    }

    public FingerPrintCheckListener mFingerPrintCheckListener;

    public void setFingerPrintCheckListener(FingerPrintCheckListener listener) {
        mFingerPrintCheckListener = listener;
    }

    public interface FingerPrintCheckListener {
        void checkSuccess();

        void checkCancel();

        void checkFail(String str);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值