我是靠谱客的博主 务实朋友,最近开发中收集的这篇文章主要介绍Android 6.0指纹识别App开发DemoAndroid 6.0指纹识别App开发Demo,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Android 6.0指纹识别App开发Demo

现在很多手机都有指纹识别的功能,这边就简单了解学习一下。
贴一张效果图:
效果图

首先声明指纹识别权限:

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

这个权限是一个normal级别的,所以不需要再运行时加判断。
这里复习一下normal 权限有哪些:

    ACCESS_LOCATION_EXTRA_COMMANDS
    ACCESS_NETWORK_STATE
    ACCESS_NOTIFICATION_POLICY
    ACCESS_WIFI_STATE
    BLUETOOTH
    BLUETOOTH_ADMIN
    BROADCAST_STICKY
    CHANGE_NETWORK_STATE
    CHANGE_WIFI_MULTICAST_STATE
    CHANGE_WIFI_STATE
    DISABLE_KEYGUARD
    EXPAND_STATUS_BAR
    GET_PACKAGE_SIZE
    INSTALL_SHORTCUT
    INTERNET
    KILL_BACKGROUND_PROCESSES
    MODIFY_AUDIO_SETTINGS
    NFC
    READ_SYNC_SETTINGS
    READ_SYNC_STATS
    RECEIVE_BOOT_COMPLETED
    REORDER_TASKS
    REQUEST_INSTALL_PACKAGES
    SET_ALARM
    SET_TIME_ZONE
    SET_WALLPAPER
    SET_WALLPAPER_HINTS
    TRANSMIT_IR
    UNINSTALL_SHORTCUT
    USE_FINGERPRINT
    VIBRATE
    WAKE_LOCK
    WRITE_SYNC_SETTINGS

运行时需要判断的权限:

  group:android.permission-group.CONTACTS
  permission:android.permission.WRITE_CONTACTS
  permission:android.permission.GET_ACCOUNTS
  permission:android.permission.READ_CONTACTS

  group:android.permission-group.PHONE
  permission:android.permission.READ_CALL_LOG
  permission:android.permission.READ_PHONE_STATE
  permission:android.permission.CALL_PHONE
  permission:android.permission.WRITE_CALL_LOG
  permission:android.permission.USE_SIP
  permission:android.permission.PROCESS_OUTGOING_CALLS
  permission:com.android.voicemail.permission.ADD_VOICEMAIL

  group:android.permission-group.CALENDAR
  permission:android.permission.READ_CALENDAR
  permission:android.permission.WRITE_CALENDAR

  group:android.permission-group.CAMERA
  permission:android.permission.CAMERA

  group:android.permission-group.SENSORS
  permission:android.permission.BODY_SENSORS

  group:android.permission-group.LOCATION
  permission:android.permission.ACCESS_FINE_LOCATION
  permission:android.permission.ACCESS_COARSE_LOCATION

  group:android.permission-group.STORAGE
  permission:android.permission.READ_EXTERNAL_STORAGE
  permission:android.permission.WRITE_EXTERNAL_STORAGE

  group:android.permission-group.MICROPHONE
  permission:android.permission.RECORD_AUDIO

  group:android.permission-group.SMS
  permission:android.permission.READ_SMS
  permission:android.permission.RECEIVE_WAP_PUSH
  permission:android.permission.RECEIVE_MMS
  permission:android.permission.RECEIVE_SMS
  permission:android.permission.SEND_SMS
  permission:android.permission.READ_CELL_BROADCASTS

具体的可以参考hongyang的这篇博客:http://blog.csdn.net/lmj623565791/article/details/50709663
好了言归正传
申明权限之后,我们需要在代码里判断下面几种情况:

设备条件判断

  • 1.设备是否支持指纹识别
  • 2.设备是否处于安全保护中(有指纹识别的手机,在使用指纹识别的时候,还需要强制设置密码或者图案解锁,如果未设置的话是不许使用指纹识别的)
  • 3.设备是否已经注册过指纹(如果用户未使用过这个指纹技术,那么只能提示用户到系统设置里面去设置)

指纹识别API调用

接下来就是调用指纹识别的API了,因为指纹识别是6.0系统才有的(当然不排除有些厂商定制系统的时候加入这些API,这里暂不考虑)。
有两种方式:

//这种使用的是v4的兼容包,推荐使用这种
FingerprintManagerCompat managerCompat = FingerprintManagerCompat.from(this);
//这种是使用系统服务,但是必须要在sdk为23以上版本才行
FingerprintManager fingerprintManager = (FingerprintManager)getSystemService(Context.FINGERPRINT_SERVICE);

这里推荐使用第一种,这样才能向下兼容。
就像运行时权限为了保持兼容性建议使用v4包的兼容方法:

ContextCompat.checkSelfPermission()
ActivityCompat.requestPermissions()
ActivityCompat.OnRequestPermissionsResultCallback
ActivityCompat.shouldShowRequestPermissionRationale()
学习地址:http://blog.csdn.net/kong_gu_you_lan/article/details/52488097

另外,这里推荐一下谷歌中国的android的开发者官网:https://developer.android.google.cn/,开发者已经可以自由的在上面查阅资料了。
调用 managerCompat.authenticate方式实现指纹识别,这个方法有5个参数,其中第三个是CancellationSignal,调用cancel 可以取消指纹识别。第四个为AuthenticationCallback,是识别之后的各种回调。这里简单记录一下代码:
工具类:FingerprintUtil.java

package com.leafact.fingerprintdemo;

import android.app.KeyguardManager;
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat;
import android.support.v4.os.CancellationSignal;

/**
 * Created by leafact on 2016/12/21.
 */

public class FingerprintUtil {
    public static CancellationSignal cancellationSignal;

    public static  void callFingerPrint(final OnCallBackListenr listener){
        FingerprintManagerCompat managerCompat = FingerprintManagerCompat.from(MyApplication.context);
        if (!managerCompat.isHardwareDetected()){ //判断设备是否支持
            if (listener != null)
                listener.onSupportFailed();
            return;
        }
        KeyguardManager keyguardManager =(KeyguardManager)MyApplication.context.getSystemService(MyApplication.context.KEYGUARD_SERVICE);
        if (!keyguardManager.isKeyguardSecure()) {//判断设备是否处于安全保护中
            if (listener != null)
            listener.onInsecurity();
            return;
        }
        if (!managerCompat.hasEnrolledFingerprints()){ //判断设备是否已经注册过指纹
            if (listener != null)
                listener.onEnrollFailed(); //未注册
            return;
        }
        if (listener != null)
            listener.onAuthenticationStart(); //开始指纹识别
        cancellationSignal  = new CancellationSignal(); //必须重新实例化,否则cancel 过一次就不能再使用了
        managerCompat.authenticate(null,0,cancellationSignal,new FingerprintManagerCompat.AuthenticationCallback(){
             // 当出现错误的时候回调此函数,比如多次尝试都失败了的时候,errString是错误信息,比如华为的提示就是:尝试次数过多,请稍后再试。
             @Override
             public void onAuthenticationError(int errMsgId, CharSequence errString) {
                 if (listener != null)
                     listener.onAuthenticationError(errMsgId ,errString );
             }

             // 当指纹验证失败的时候会回调此函数,失败之后允许多次尝试,失败次数过多会停止响应一段时间然后再停止sensor的工作
             @Override
             public void onAuthenticationFailed() {
                 if (listener != null)
                     listener.onAuthenticationFailed();
             }

             @Override
             public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
                 if (listener != null)
                     listener.onAuthenticationHelp(helpMsgId,helpString);
             }

             // 当验证的指纹成功时会回调此函数,然后不再监听指纹sensor
             @Override
             public void onAuthenticationSucceeded(FingerprintManagerCompat.AuthenticationResult result) {
                 if (listener != null)
                     listener.onAuthenticationSucceeded(result);
             }
         ;
        },null);

    }
    interface  OnCallBackListenr{
        void onSupportFailed();
        void onInsecurity();
        void onEnrollFailed();
        void onAuthenticationStart();
        void onAuthenticationError(int errMsgId, CharSequence errString);
        void onAuthenticationFailed();
        void onAuthenticationHelp(int helpMsgId, CharSequence helpString);
        void onAuthenticationSucceeded(FingerprintManagerCompat.AuthenticationResult result);
    }

    public static  void cancel(){
        if (cancellationSignal != null)
            cancellationSignal.cancel();
    }
}

这里写一个 OnCallBackListenr 进行回调封装起来。
调用类:MainActivity.java

package com.leafact.fingerprintdemo;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private Context mContext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
    }
    public void onFingerprintClick(View v){

        FingerprintUtil.callFingerPrint(new FingerprintUtil.OnCallBackListenr() {
            AlertDialog dialog;
            @Override
            public void onSupportFailed() {
                showToast("当前设备不支持指纹");
            }

            @Override
            public void onInsecurity() {
                showToast("当前设备未处于安全保护中");
            }

            @Override
            public void onEnrollFailed() {
                showToast("请到设置中设置指纹");
            }

            @Override
            public void onAuthenticationStart() {
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                View view = LayoutInflater.from(mContext).inflate(R.layout.layout_fingerprint,null);
                initView(view);
                builder.setView(view);
                builder.setCancelable(false);
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        handler.removeMessages(0);
                        FingerprintUtil.cancel();
                    }
                });
                dialog = builder.create();
                dialog.show();
            }

            @Override
            public void onAuthenticationError(int errMsgId, CharSequence errString) {
                showToast(errString.toString());
                if (dialog != null  &&dialog.isShowing()){
                    dialog.dismiss();
                    handler.removeMessages(0);
                }
            }

            @Override
            public void onAuthenticationFailed() {
                showToast("解锁失败");
            }

            @Override
            public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
                showToast(helpString.toString());
            }

            @Override
            public void onAuthenticationSucceeded(FingerprintManagerCompat.AuthenticationResult result) {
                showToast("解锁成功");
                if (dialog != null  &&dialog.isShowing()){
                    dialog.dismiss();
                    handler.removeMessages(0);
                }

            }
        });
    }
    private Handler handler= new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0){
                int i = postion % 5;
                if (i == 0){
                    tv[4].setBackground(null);
                    tv[i].setBackgroundColor(getResources().getColor(R.color.colorAccent));
                }
                else{
                     tv[i].setBackgroundColor(getResources().getColor(R.color.colorAccent));
                     tv[i-1].setBackground(null);
                }
                postion++;
                handler.sendEmptyMessageDelayed(0,100);
            }
        }
    };
    TextView[] tv = new TextView[5];
    private int postion = 0;
    private void initView(View view) {
        postion = 0;
        tv[0] = (TextView) view.findViewById(R.id.tv_1);
        tv[1] = (TextView) view.findViewById(R.id.tv_2);
        tv[2] = (TextView) view.findViewById(R.id.tv_3);
        tv[3] = (TextView) view.findViewById(R.id.tv_4);
        tv[4] = (TextView) view.findViewById(R.id.tv_5);
        handler.sendEmptyMessageDelayed(0,100);
    }


    public void showToast(String name ){
        Toast.makeText(MainActivity.this,name,Toast.LENGTH_SHORT).show();
    }
}

这里我加入了一个很简单的动画。
剩下的代码就不贴了,需要的话可以下载源码
源码地址 :http://download.csdn.net/detail/leafact/9717825

想深入的了解的同学可以参考这篇文章 http://blog.csdn.net/createchance/article/details/51991764

最后

以上就是务实朋友为你收集整理的Android 6.0指纹识别App开发DemoAndroid 6.0指纹识别App开发Demo的全部内容,希望文章能够帮你解决Android 6.0指纹识别App开发DemoAndroid 6.0指纹识别App开发Demo所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(45)

评论列表共有 0 条评论

立即
投稿
返回
顶部