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>
这是一个非常简易的指纹认证界面,相信没什么需要解释的地方。界面大致样式如下图所示。
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,整个指纹认证过程就此结束。
打开应用之后会立刻弹出指纹认证对话框,此时先使用错误的手指来进行认证:
可以看到,当指纹验证失败的时候,会在界面上显示相应的错误提示信息。
接下来使用正确的手指来进行认证:
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 对话框取消
识别对话框只能点取消按钮关闭,点击其他区域不能关闭!
在FingerprintDialogFragment
的onCreateView
中增加如下代码
@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;
}