Android 指纹识别

这篇具有很好参考价值的文章主要介绍了Android 指纹识别。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Android 指纹识别

Android 从 6.0 系统开始就支持指纹认证功能。

将指纹认证功能使用到 APP 的功能逻辑当中是有很多功能场景的,比如说金融银行类 APP 可以使用指纹认证来快速登录,股票证券类 APP 可以使用指纹认证来操作和交易等等。

  • FingerprintManager : 指纹管理工具类
  • FingerprintManager.AuthenticationCallback :使用验证的时候传入该接口,通过该接口进行验证结果回调
  • FingerprintManager.CryptoObject: FingerprintManager 支持的分装加密对象的类

以上是28以下API 中使用的类 在Android 28版本中google 宣布使用Androidx 库代替Android库,所以在28版本中Android 推荐使用androidx库中的类 所以在本文中我 使用的是推荐是用的FingerprintManagerCompat 二者的使用的方式基本相似

一、代码

1.0 添加权限

<uses-permission android:name="android.permission.USE_FINGERPRINT" />

1.1 创建验证对话框布局

开始编写指纹认证界面,新建 fingerprint_dialog.xml,代码如下所示:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/image_finger"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/ic_fp_40px" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:text="请验证指纹解锁"
        android:textColor="#000"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/error_msg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="5dp"
        android:maxLines="1"
        android:textColor="#f45"
        android:textSize="12sp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:layout_marginTop="10dp"
        android:background="#ccc" />

    <TextView
        android:id="@+id/cancel"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:text="取消"
        android:textColor="#5d7883"
        android:textSize="16sp" />

</LinearLayout>

这是一个非常简易的指纹认证界面,相信没什么需要解释的地方。界面大致样式如下图所示。

Android 指纹识别,android,指纹识别,java

Google 也特意提供了一套指纹认证的组图,可以 点击这里 查看和下载。

1.2 创建FingerprintDialogFragment

接着我们创建一个 FingerprintDialogFragment 类,并让它继承自 DialogFragment,用于作为提示用户进行指纹认证的对话框,代码如下所示:

@TargetApi(23)
public class FingerprintDialogFragment extends DialogFragment {

    private FingerprintManager fingerprintManager;

    private CancellationSignal mCancellationSignal;

    private Cipher mCipher;

    private LoginActivity mActivity;

    private TextView errorMsg;

    /**
     * 标识是否是用户主动取消的认证。
     */
    private boolean isSelfCancelled;

    public void setCipher(Cipher cipher) {
        mCipher = cipher;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = (LoginActivity) getActivity();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fingerprintManager = getContext().getSystemService(FingerprintManager.class);
        setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Material_Light_Dialog);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fingerprint_dialog, container, false);
        errorMsg = v.findViewById(R.id.error_msg);
        TextView cancel = v.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                stopListening();
            }
        });
        return v;
    }

    @Override
    public void onResume() {
        super.onResume();
        
        startListening(mCipher);
    }

    @Override
    public void onPause() {
        super.onPause();
        
        stopListening();
    }

    private void startListening(Cipher cipher) {
        isSelfCancelled = false;
        mCancellationSignal = new CancellationSignal();
        fingerprintManager.authenticate(new FingerprintManager.CryptoObject(cipher), mCancellationSignal, 0, new FingerprintManager.AuthenticationCallback() {
            @Override
            public void onAuthenticationError(int errorCode, CharSequence errString) {
                if (!isSelfCancelled) {
                    errorMsg.setText(errString);
                    if (errorCode == FingerprintManager.FINGERPRINT_ERROR_LOCKOUT) {
                        Toast.makeText(mActivity, errString, Toast.LENGTH_SHORT).show();
                        dismiss();
                    }
                }
            }

            @Override
            public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
                errorMsg.setText(helpString);
            }

            @Override
            public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
                Toast.makeText(mActivity, "指纹认证成功", Toast.LENGTH_SHORT).show();
                mActivity.onAuthenticated();
            }

            @Override
            public void onAuthenticationFailed() {
                errorMsg.setText("指纹认证失败,请再试一次");
            }
        }, null);
    }

    private void stopListening() {
        if (mCancellationSignal != null) {
            mCancellationSignal.cancel();
            mCancellationSignal = null;
            isSelfCancelled = true;
        }
    }

}

setCipher() 方法用于接受一个 Cipher 对象,这个参数在待会进行指纹认证的时候会用到。

1.3 解释dialog中的内容

接下来几个生命周期方法都很简单,在 onAttach() 方法中获取了 Activity 的实例,在 onCreate() 方法获取了 FingerprintManager 的实例,在 onCreateView() 方法中加载了我们刚刚创建的 fingerprint_dialog.xml 布局,都是一些常规操作。

紧接着重点的要来了,在 onResume() 方法中调用了 startListening() 方法开始指纹认证监听,在 onPause() 方法中调用了 stopListening() 方法停止指纹认证监听。为什么要这么做呢?因为指纹传感器和摄像头类似,是不能多个程序同时使用的,因此任何一个程序都不应该在非前台时刻占用着指纹传感器的资源,所以需要在 onPause() 方法中及时释放资源。

那么,现在我们只需要把所有的目光都放在 startListening() 和 stopListening() 这两个方法上就可以了。在 startListening() 方法中,调用了 FingerprintManager 的 authenticate() 方法来开启指纹指纹监听。authenticate() 方法接收五个参数,第一个参数是 CryptoObject 对象,这里我们只需要将刚才传入的 Cipher 对象包装成 CryptoObject 对象就可以了。第二个参数是 CancellationSignal 对象,可以使用它来取消指纹认证操作。第三个参数是可选参数,官方的建议是直接传 0 就可以了。第四个参数用于接收指纹认证的回调,上述代码中我将所有的回调可能都进行了界面提示,方便大家观察。第五个参数用于指定处理回调的 Handler,这里直接传 null 表示回调到主线程即可。

而在 stopListening() 方法中的逻辑则简单得多了,我们只需要调用 CancellationSignal 的 cancel() 方法将指纹认证操作取消就可以了。

这样我们就将 FingerprintDialogFragment 中的代码全部完成了,这段代码可以直接复制到任意项目当中来作为指纹认证提醒对话框。

1.4 创建登陆界面

最后,我们再来编写一个简单的登录界面,整个指纹认证过程就完整了。创建 LoginActivity,代码如下所示:

public class LoginActivity extends AppCompatActivity {

    private static final String DEFAULT_KEY_NAME = "default_key";

    KeyStore keyStore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        if (supportFingerprint()) {
            initKey();
            initCipher();
        }
    }

    public boolean supportFingerprint() {
        if (Build.VERSION.SDK_INT < 23) {
            Toast.makeText(this, "您的系统版本过低,不支持指纹功能", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            KeyguardManager keyguardManager = getSystemService(KeyguardManager.class);
            FingerprintManager fingerprintManager = getSystemService(FingerprintManager.class);
            if (!fingerprintManager.isHardwareDetected()) {
                Toast.makeText(this, "您的手机不支持指纹功能", Toast.LENGTH_SHORT).show();
                return false;
            } else if (!keyguardManager.isKeyguardSecure()) {
                Toast.makeText(this, "您还未设置锁屏,请先设置锁屏并添加一个指纹", Toast.LENGTH_SHORT).show();
                return false;
            } else if (!fingerprintManager.hasEnrolledFingerprints()) {
                Toast.makeText(this, "您至少需要在系统设置中添加一个指纹", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return true;
    }

    @TargetApi(23)
    private void initKey() {
        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);
        }
    }

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

    private void showFingerPrintDialog(Cipher cipher) {
        FingerprintDialogFragment fragment = new FingerprintDialogFragment();
        fragment.setCipher(cipher);
        fragment.show(getFragmentManager(), "fingerprint");
    }

    public void onAuthenticated() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

}

**首先在 onCreate() 方法中,调用了 supportFingerprint() 方法来判断当前设备是否支持指纹认证功能。**这一点是非常重要的,因为当设备不支持指纹认证的时候,还需要及时切换到如图案、密码等其他的认证方式。

当设备支持指纹认证的时候,再分为两步,第一步生成一个对称加密的 Key,第二步生成一个 Cipher 对象,这都是 Android 指纹认证 API 要求的标准用法。得到了 Cipher 对象之后,我们创建 FingerprintDialogFragment 的实例,并将 Cipher 对象传入,再将 FingerprintDialogFragment 显示出来就可以了。

1.5 认证成功跳到主界面

当指纹认证成功之后,会在 FingerprintDialogFragment 的回调当中调用 LoginActivity 的 onAuthenticated() 方法,然后界面会跳转到 MainActivity,整个指纹认证过程就此结束。

打开应用之后会立刻弹出指纹认证对话框,此时先使用错误的手指来进行认证:

Android 指纹识别,android,指纹识别,java

可以看到,当指纹验证失败的时候,会在界面上显示相应的错误提示信息。

接下来使用正确的手指来进行认证:

Android 指纹识别,android,指纹识别,java

OK,指纹验证成功,并自动跳转到了 MainActivity 界面。

源码

1.6 手机验证的次数

手机指纹识别的验证的次数是有限制的,一段时间内,大概只能识别5次。5次后就要等大概1分钟后才能重新识别。

@TargetApi(23)
public class FingerprintDialogFragment extends DialogFragment {

    private FingerprintManager fingerprintManager;

    private CancellationSignal mCancellationSignal;

    private Cipher mCipher;

    private LoginActivity mActivity;

    private TextView errorMsg;

    //识别的次数
    private int mCount = 5;

    /**
     * 标识是否是用户主动取消的认证。
     */
    private boolean isSelfCancelled;

    public void setCipher(Cipher cipher) {
        mCipher = cipher;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = (LoginActivity) getActivity();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fingerprintManager = getContext().getSystemService(FingerprintManager.class);
        setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Material_Light_Dialog);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        //不消失
        getDialog().setCancelable(false);
        getDialog().setCanceledOnTouchOutside(false);
        //点击返回键不消失
        getDialog().setOnKeyListener((dialog, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_BACK)
                return true;
            return false;
        });
        View v = inflater.inflate(R.layout.fingerprint_dialog, container, false);
        errorMsg = v.findViewById(R.id.error_msg);
        TextView cancel = v.findViewById(R.id.cancel);
        cancel.setOnClickListener(v1 -> {
            dismiss();
            stopListening();
        });

        return v;
    }

    @Override
    public void onResume() {
        super.onResume();

        startListening(mCipher);
    }

    @Override
    public void onPause() {
        super.onPause();

        stopListening();
    }

    private void startListening(Cipher cipher) {
        isSelfCancelled = false;
        mCancellationSignal = new CancellationSignal();
        fingerprintManager.authenticate(new FingerprintManager.CryptoObject(cipher), mCancellationSignal, 0, new FingerprintManager.AuthenticationCallback() {
            @Override
            public void onAuthenticationError(int errorCode, CharSequence errString) {
                Log.i("zxd", "onAuthenticationError: " + mCount);
                if (!isSelfCancelled) {
                    errorMsg.setText(errString);
                    if (errorCode == FingerprintManager.FINGERPRINT_ERROR_LOCKOUT) {
                        Toast.makeText(mActivity, errString, Toast.LENGTH_SHORT).show();
                        dismiss();
                    }
                    mCount = 5;
                }
            }

            @Override
            public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
                errorMsg.setText(helpString);
            }

            @Override
            public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
                Toast.makeText(mActivity, "指纹认证成功", Toast.LENGTH_SHORT).show();
                mActivity.onAuthenticated();
            }

            @Override
            public void onAuthenticationFailed() {
                if (mCount > 1) {
                    mCount--;
                    errorMsg.setText("指纹不匹配,还可以尝试" + mCount + "次");
                } else
                    errorMsg.setText("指纹认证失败,请再试一次");
            }
        }, null);
    }

    private void stopListening() {
        if (mCancellationSignal != null) {
            mCancellationSignal.cancel();
            mCancellationSignal = null;
            isSelfCancelled = true;
        }
    }

}

onAuthenticationError中,可以使用handler提示“延迟多少s”才能继续识别。

对话框中有“取消”按钮,如果在识别的过程中,识别2次,再继续打开对话框还是从5次开始,这是不对的,因为手机的次数耗掉了2次!

public class LoginActivity extends AppCompatActivity {

    private static final String DEFAULT_KEY_NAME = "default_key";

    KeyStore keyStore;
    private FingerprintDialogFragment fragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        if (supportFingerprint()) {
            initKey();
            initCipher();
        }
        //再次打开指纹识别
        ImageView iv = findViewById(R.id.image_finger);
        iv.setOnClickListener(v -> {
            if (fragment != null) {
                fragment.show(getSupportFragmentManager(), "fingerprint");
            }
        });
    }

    public boolean supportFingerprint() {
        if (Build.VERSION.SDK_INT < 23) {
            Toast.makeText(this, "您的系统版本过低,不支持指纹功能", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            KeyguardManager keyguardManager = getSystemService(KeyguardManager.class);
            FingerprintManager fingerprintManager = getSystemService(FingerprintManager.class);
            if (!fingerprintManager.isHardwareDetected()) {
                Toast.makeText(this, "您的手机不支持指纹功能", Toast.LENGTH_SHORT).show();
                return false;
            } else if (!keyguardManager.isKeyguardSecure()) {
                Toast.makeText(this, "您还未设置锁屏,请先设置锁屏并添加一个指纹", Toast.LENGTH_SHORT).show();
                return false;
            } else if (!fingerprintManager.hasEnrolledFingerprints()) {
                Toast.makeText(this, "您至少需要在系统设置中添加一个指纹", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return true;
    }

    @TargetApi(23)
    private void initKey() {
        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);
        }
    }

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

    private void showFingerPrintDialog(Cipher cipher) {
        fragment = new FingerprintDialogFragment();
        fragment.setCipher(cipher);
        fragment.show(getSupportFragmentManager(), "fingerprint");
    }

    public void onAuthenticated() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }
}

将fragment提取出来,点击的再次显示对话框的时候,直接显示就行,不需要重新创建

1.7 手机验证失败,增加抖动效果

利用识别对话框中的指纹图片,进行左右晃动

@TargetApi(23)
public class FingerprintDialogFragment extends DialogFragment {

    ....

    private TranslateAnimation mAnimation;
    private ImageView mShakeImage;
    ...

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    	...
        //创建动画
        mShakeImage = v.findViewById(R.id.image_finger);
        mAnimation = new TranslateAnimation(0, 5, 0, 0);
        mAnimation.setDuration(800);
        mAnimation.setInterpolator(new CycleInterpolator(8));

        return v;
    }

    private void startListening(Cipher cipher) {
        isSelfCancelled = false;
        mCancellationSignal = new CancellationSignal();
        fingerprintManager.authenticate(new FingerprintManager.CryptoObject(cipher), mCancellationSignal, 0, new FingerprintManager.AuthenticationCallback() {
            @Override
            public void onAuthenticationError(int errorCode, CharSequence errString) {
                Log.i("zxd", "onAuthenticationError: " + mCount);
                if (!isSelfCancelled) {
                    errorMsg.setText(errString);
                    if (errorCode == FingerprintManager.FINGERPRINT_ERROR_LOCKOUT) {
                        Toast.makeText(mActivity, errString, Toast.LENGTH_SHORT).show();
                        dismiss();
                    }
                    mCount = 5;
                }
            }

            @Override
            public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
                errorMsg.setText(helpString);
            }

            @Override
            public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
                Toast.makeText(mActivity, "指纹认证成功", Toast.LENGTH_SHORT).show();
                mActivity.onAuthenticated();
            }

            @Override
            public void onAuthenticationFailed() {
                if (mCount > 1) {
                    mCount--;
                    errorMsg.setText("指纹不匹配,还可以尝试" + mCount + "次");
                } else
                    errorMsg.setText("指纹认证失败,请再试一次");
                mShakeImage.startAnimation(mAnimation);
            }
        }, null);
    }

    ...
}

动画也可以使用资源文件

Animation shakeAnimation = AnimationUtils.loadAnimation(PatternCheckActivity.this, R.anim.shake);
binding.patternCheckTv.startAnimation(shakeAnimation);

shake.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="1000"
    android:fromXDelta="0"
    android:interpolator="@anim/cycle_7"
    android:toXDelta="10" />

cycle_7.xml

<cycleInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
    android:cycles="7" />

1.8 对话框取消

识别对话框只能点取消按钮关闭,点击其他区域不能关闭!

FingerprintDialogFragmentonCreateView中增加如下代码

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    //不消失
    getDialog().setCancelable(false);
    getDialog().setCanceledOnTouchOutside(false);
    //点击返回键不消失
    getDialog().setOnKeyListener((dialog, keyCode, event) -> {
        if (keyCode == KeyEvent.KEYCODE_BACK)
            return true;
        return false;
    });
    View v = inflater.inflate(R.layout.fingerprint_dialog, container, false);
    errorMsg = v.findViewById(R.id.error_msg);
    TextView cancel = v.findViewById(R.id.cancel);
    cancel.setOnClickListener(v1 -> {
        dismiss();
        stopListening();
    });

    return v;
}

1.9 登陆界面修改

到1.8基本上可以了,但是我看银行指纹登陆界面不错,就想实现一下

首先修改下activity_login.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activity.LoginActivity">

    <com.zg.smarttime.widget.CircleImageView
        android:id="@+id/login_image"
        android:layout_width="@dimen/dp_100"
        android:layout_height="@dimen/dp_100"
        android:layout_marginTop="@dimen/dp_20"
        android:src="@drawable/autherimg"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/login_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="@dimen/dp_8"
        android:text="欢迎回来"
        android:textColor="@android:color/holo_orange_dark"
        android:textSize="@dimen/sp_20"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/login_image" />

    <ImageView
        android:id="@+id/image_finger"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/dp_100"
        android:src="@drawable/ic_fp_40px"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/dp_140"
        android:gravity="center"
        android:padding="@dimen/dp_8"
        android:text="点击进行指纹登陆"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/image_finger" />

</androidx.constraintlayout.widget.ConstraintLayout>

增加了一个圆形头像,问好的文本,指纹的图片,用于重新打开识别对话框,一个文本提示用户进行识别

public class LoginActivity extends AppCompatActivity {

    private static final String DEFAULT_KEY_NAME = "default_key";

    KeyStore keyStore;
    private FingerprintDialogFragment fragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        if (supportFingerprint()) {
            initKey();
            initCipher();
        }
        //再次打开指纹识别
        ImageView iv = findViewById(R.id.image_finger);
        iv.setOnClickListener(v -> {
            if (fragment != null) {
                fragment.show(getSupportFragmentManager(), "fingerprint");
            }
        });

        TextView loginTv = findViewById(R.id.login_tv);
        loginTv.setText(DateUtils.getDateSx() + "!");
    }

    public boolean supportFingerprint() {
        if (Build.VERSION.SDK_INT < 23) {
            Toast.makeText(this, "您的系统版本过低,不支持指纹功能", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            KeyguardManager keyguardManager = getSystemService(KeyguardManager.class);
            FingerprintManager fingerprintManager = getSystemService(FingerprintManager.class);
            if (!fingerprintManager.isHardwareDetected()) {
                Toast.makeText(this, "您的手机不支持指纹功能", Toast.LENGTH_SHORT).show();
                return false;
            } else if (!keyguardManager.isKeyguardSecure()) {
                Toast.makeText(this, "您还未设置锁屏,请先设置锁屏并添加一个指纹", Toast.LENGTH_SHORT).show();
                return false;
            } else if (!fingerprintManager.hasEnrolledFingerprints()) {
                Toast.makeText(this, "您至少需要在系统设置中添加一个指纹", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return true;
    }

    @TargetApi(23)
    private void initKey() {
        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);
        }
    }

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

    private void showFingerPrintDialog(Cipher cipher) {
        fragment = new FingerprintDialogFragment();
        fragment.setCipher(cipher);
        fragment.show(getSupportFragmentManager(), "fingerprint");
    }

    public void onAuthenticated() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }
}

问好代码,根据日历中hour进行判断

/***
 * 根据Calendar的hour来判断
 */
public static String getDateSx() {
    String nihao = "";
    Calendar cal = Calendar.getInstance();
    int hour = cal.get(Calendar.HOUR_OF_DAY);
    if (hour >= 6 && hour < 8) {
        System.out.println("早上好");
        nihao = "早上好";
    } else if (hour >= 8 && hour < 11) {
        System.out.print("上午好");
        nihao = "上午好";
    } else if (hour >= 11 && hour < 13) {
        System.out.print("中午好");
        nihao = "中午好";
    } else if (hour >= 13 && hour < 18) {
        System.out.print("下午好");
        nihao = "下午好";
    } else {
        System.out.print("晚上好");
        nihao = "晚上好";
    }
    return nihao;
}

二、参考

Android指纹识别API讲解,一种更快更好的用户体验

Android指纹识别认识和基本使用详解

Android 指纹识别(给应用添加指纹解锁)

Google代码

kt代码

DialogFragment点击背景透明区域不可取消的设置文章来源地址https://www.toymoban.com/news/detail-600436.html

到了这里,关于Android 指纹识别的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【老生谈算法】基于matlab的指纹处理和识别算法详解及程序源码——指纹识别算法

    大家好,今天给大家介绍基于matlab的指纹处理和识别程序项目设计与原理。 文章目录: 文件列表: main.m--------主程序。 imgread.m-----图像读取函数。 imgchg.m------将真彩色图像转换为灰度图像的函数。 imgcut.m------图像分割函数。 imgflt.m------图像去噪滤波。 imgdir.m------计算方向图

    2024年02月05日
    浏览(37)
  • 指纹识别(二)—— 光学指纹场景使用OLED HBM功能

    指纹系列文章: 指纹识别(一)—— 电容式、光学式、超声波式介绍 指纹识别(二)—— 光学指纹场景使用OLED HBM功能 目前,背光高亮分为局部高亮和全局高亮,其中,全局高亮的亮度高而且稳定,使得指纹识别成功率比局部高亮的识别成功率高。但是,全局高亮也存在一

    2024年02月09日
    浏览(47)
  • 渗透测试 | 指纹识别

    0x00 免责声明         本文仅限于学习讨论与技术知识的分享,不得违反当地国家的法律法规。对于传播、利用文章中提供的信息而造成的任何直接或者间接的后果及损失,均由使用者本人负责,本文作者不为此承担任何责任,一旦造成后果请自行承担!            

    2024年02月07日
    浏览(30)
  • 指纹识别q

    FTIR(Frustrated Total Internal Reflection),受抑全内反射。在屏幕的夹层中加入LED光线,当用户按下屏幕时,使夹层的光线造成不同的反射效果,感应器接收光线变化而捕捉用户的施力点。 明显的缺点:体积太大。薄膜晶体管TFT( Thin Film Transistor)是目前制造大型LCD面板的成熟且廉

    2023年04月17日
    浏览(30)
  • 指纹识别描述

      指纹由于其终身不变性、唯一性和方便性, 几乎已成为生物特征识别的代名 词。通常我们说的指纹就是人的手指末端正面皮肤上凸凹不平的纹线,纹线规律地排列  形成不同的纹型。而本节所讲的指纹是指网站 CMS   指 纹识别、计算机操作系统及 W  eb    容器的指纹识别

    2024年02月19日
    浏览(36)
  • 竞赛保研 opencv 图像识别 指纹识别 - python

    🔥 优质竞赛项目系列,今天要分享的是 🚩 基于机器视觉的指纹识别系统 🥇学长这里给一个题目综合评分(每项满分5分) 难度系数:3分 工作量:3分 创新点:4分 该项目较为新颖,适合作为竞赛课题方向,学长非常推荐! 🧿 更多资料, 项目分享: https://gitee.com/dancheng-seni

    2024年02月03日
    浏览(41)
  • 【毕设选题】opencv 图像识别 指纹识别 - python

    🔥 这两年开始毕业设计和毕业答辩的要求和难度不断提升,传统的毕设题目缺少创新和亮点,往往达不到毕业答辩的要求,这两年不断有学弟学妹告诉学长自己做的项目系统达不到老师的要求。 为了大家能够顺利以及最少的精力通过毕设,学长分享优质毕业设计项目,今天

    2024年02月07日
    浏览(34)
  • OpenCV实例(五)指纹识别

    作者:Xiou 指纹识别,简单来说就是判断一枚未知的指纹属于一组已知指纹里面的哪个人的指纹。这个识别过程与我们在村口识别远处走来的人类似,首先,要抓住主要特征,二者的主要特征要一致;其次,二者要有足够多的主要特征一致。满足了这两个条件就能判断一枚指

    2024年02月11日
    浏览(22)
  • 最新CMS指纹识别技术

    CMS(Content Management System,内容管理系统),又称整站系统或文章系统,用于网站内容管理。用户只需下载对应的CMS软件包,部署、搭建后就可以直接使用CMS。各CMS具有独特的结构命名规则和特定的文件内容。 目前常见的CMS有DedeCMS、Discuz、PHPWeb、PHPWind、PHPCMS、ECShop、Dvbbs、

    2024年02月11日
    浏览(40)
  • 指纹识别综述(3): 特征提取

    本文主要基于《Handbook of Fingerprint Recognition》第三版第三章“Fingerprint Analysis and Representation”的内容。本文会不定期更新,以反映一些新的进展和思考。 利用指纹采集技术获取的指纹图像通常为二维灰度图像,其中脊线是暗的,而谷线是亮的。虽然指纹图像并不是深度图像,

    2024年02月05日
    浏览(54)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包