欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android 指纹锁工具类

程序员文章站 2022-07-03 17:20:34
android sdk版本超过23以上就可以支持添加指纹识别功能,因此可以为自己的应用添加指纹锁这个概念的启动限制。高于23,少于28版本的,调用方法后如果屏幕前盖有指纹工具的话会显示指纹锁出来,高于28版本会出来指纹锁识别对话框,由系统本身提供,有回调函数支持各种事件,记录下具体的识别工具类。import android.app.Activity;import android.app.KeyguardManager;import android.content.Context;import a...

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);
    }
}

 

本文地址:https://blog.csdn.net/gan303/article/details/110226587

相关标签: android