Android指纹解锁
Android6.0及以上系统支持指纹识别解锁功能:项目中用到,特此抽离出来,备忘。
功能是这样的:在用户将app切换到后台运行(超过一定的时长,比方说30秒),再进入程序中的时候就会弹出指纹识别的界面。用户输入指纹,解锁成功。指纹识别的模块其实很简单啦,google的api已经封装好了,我们只需要学会调用就ok了。
思路:
在用户将程序切换到后台的时候需要有一个方法计时,这样的方法写在哪里呢,对,要写在service中。在Activity中开启服务:
Intentintent=newIntent("com.example.fingureprint.services.JudgeFingureService");
intent.setPackage(getPackageName());
startService(intent);
intent.setpackage(getPackageName);在6.0及以上系统中启动服务必须加上这句。
服务不要忘记在清单文件中注册幺。
复制代码
android:name="com.example.fingureprint.services.JudgeFingureService"
android:enabled="true">
复制代码
在服务中onStart()开启一个线程:
复制代码
newThread(){
publicvoidrun(){
try{
while(true){
Thread.sleep(1000);
if(isAppOnForeground()){
Log.i("前台运行","time"+countnumber);
if(countnumber>30){
if(!"com.example.fingureprint.FingureAriseActivity".equals(listActivity())){
Intentmyintent=newIntent();
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(InterruptedExceptione){
e.printStackTrace();
}
};
}.start();
复制代码
计时用了个while死循环,让thread睡一秒。哈哈,没有用Handler是不是很简单。
判断程序是否在后台运行:
复制代码
/
判断程序在前台运行的方法
@return
/
publicbooleanisAppOnForeground(){
ActivityManagersystemService=(ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
ListrunningAppProcesses=systemService.getRunningAppProcesses();
if(runningAppProcewww.tt951.comsses==null)returnfalse;
for(RunningAppProcessInfoprocesses:runningAppProcesses){
if(processes.processName.equals("com.example.fingureprint")&&processes.importance==RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
returntrue;
}
}
returnfalse;
}
复制代码
有一个小细节,当用户从后台切换到前台,但是用户没有解锁,又切换到后台,过三十秒后切换到前台,这时候不能再跳出手势解锁界面了吧。
解决:1.设置下手势界面的启动方式。2.检测程序的当前运行界面。
复制代码
/
判断当前运行在前台的Activity
/
@SuppressWarnings("deprecation")
publicStringlistActivity(){
ActivityManagersystemService=(ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
ListrunningTasks=systemService.getRunningTasks(1);
RunningTaskInforunningTaskInfo=runningwww.baiyuewang.netTasks.get(0);
ComponentNamecomponent=runningTaskInfo.topActivity;
StringclassName=component.getClassName();
returnclassName;
}
复制代码
下面讲一下指纹识别的api:在6.0及以上的v4包下:
需要在清单文件中添加权限:
用到的类有FingerprintManagerCompat,此类中的api可以检测您的手机是否有指纹传感器,手机有没有录入过指纹。
|
|