Android6.0及以上系统支持指纹识别解锁功能:项目中用到,特此抽离出来,备忘。
功能是这样的:在用户将app切换到后台运行(超过一定的时长,比方说30秒),再进入程序中的时候就会弹出指纹识别的界面。用户输入指纹,解锁成功。指纹识别的模块其实很简单啦,google的api已经封装好了,我们只需要学会调用就ok了。
思路:
在用户将程序切换到后台的时候需要有一个方法计时,这样的方法写在哪里呢,对,要写在service中。在Activity中开启服务:
Intent intent = new Intent("com.example.fingureprint.services.JudgeFingureService");intent.setPackage(getPackageName());startService(intent);
intent.setpackage(getPackageName);在6.0及以上系统中启动服务必须加上这句。
服务不要忘记在清单文件中注册幺。
<!--注册判断指纹密码开启的服务--><service android:name="com.example.fingureprint.services.JudgeFingureService"android:enabled="true"><intent-filter ><action android:name="com.example.fingureprint.services.JudgeFingureService"/></intent-filter></service>
在服务中onStart()开启一个线程:
new Thread(){public void run() {try {while(true){Thread.sleep(1000);if(isAppOnForeground()){Log.i("前台运行", "time"+countnumber);if(countnumber>30){if(!"com.example.fingureprint.FingureAriseActivity".equals(listActivity())){Intent myintent = new Intent();myintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);myintent.setClass(getApplicationContext(),FingureAriseActivity.class);startActivity(myintent);}countnumber = 0;}else{countnumber = 0;}}else{Log.i("后台运行", "time"+countnumber);countnumber ++;}}} catch (InterruptedException e) {e.printStackTrace();}};}.start();
计时用了个while死循环,让thread睡一秒。哈哈,没有用Handler是不是很简单。
判断程序是否在后台运行:
/** * 判断程序在前台运行的方法 * @return */public boolean isAppOnForeground() {ActivityManager systemService = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);List<RunningAppProcessInfo> runningAppProcesses = systemService.getRunningAppProcesses();if(runningAppProcesses==null) return false;for(RunningAppProcessInfo processes: runningAppProcesses){if(processes.processName.equals("com.example.fingureprint")&&processes.importance==RunningAppProcessInfo.IMPORTANCE_FOREGROUND){return true;}}return false;}
有一个小细节,当用户从后台切换到前台,但是用户没有解锁,又切换到后台,过三十秒后切换到前台,这时候不能再跳出手势解锁界面了吧。
解决:1.设置下手势界面的启动方式。2.检测程序的当前运行界面。
/** * 判断当前运行在前台的Activity */@SuppressWarnings("deprecation")public String listActivity(){ActivityManager systemService = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);List<RunningTaskInfo> runningTasks = systemService.getRunningTasks(1);RunningTaskInfo runningTaskInfo = runningTasks.get(0);ComponentName component = runningTaskInfo.topActivity;String className = component.getClassName();return className;}
下面讲一下指纹识别的api:在6.0及以上的v4包下:
需要在清单文件中添加权限:
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
用到的类有 FingerprintManagerCompat,此类中的api可以检测您的手机是否有指纹传感器,手机有没有录入过指纹。
AuthenticationCallback,可以继承此类,分别重写里面的方法,用来接收指纹识别的结果:
具体的可以下载下面的demo.
地址:demo
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。