android M 指纹api小示例

最近有个android M 项目上加入了指纹器件,需要测试指纹的录入和解锁,看了下M 自带的api后简单的做了实现。

主要是frameworks/base/core/java/android/hardware/fingerprint下的FingerprintManager类。

还有就是/frameworks/base/services/core/java/com/android/server/fingerprint下的FingerprintService.java


源码:

package xxxx.xxx.xxxx

import android.app.Activity;
import android.view.KeyEvent;
import android.content.pm.ActivityInfo;
import android.content.Intent;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.SystemProperties;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import android.content.Context;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import android.hardware.fingerprint.Fingerprint;
import android.hardware.fingerprint.FingerprintManager;
import android.hardware.fingerprint.FingerprintManager.AuthenticationCallback;
import android.hardware.fingerprint.FingerprintManager.AuthenticationResult;
import android.hardware.fingerprint.FingerprintManager.RemovalCallback;
import android.os.CancellationSignal;
import java.util.List;
import android.os.Vibrator;

public class TestFingerPrint extends Activity implements View.OnClickListener {
    private static final String TAG = "TestFingerPrint";
    private RoundProgressBar enrollRoundPrg;//my progressbar,you can also define yours
    private boolean mEnrolling;

    private static Handler mOutHandler = null;
    private int ID = -1;
    private String mResult = null;
    private int pass = 0;
    private PowerManager.WakeLock mWakeLock;
    private boolean mbStarted = false;
    private Button mPass = null;
    private Button mFail = null;
    private Button mReset = null;
    private byte[] mToken = new byte[69];//i hate this
    private Vibrator mVibrator;

    private FingerprintManager mFingerprintManager;
    private CancellationSignal mEnrollmentCancel;

    public static void setHandler(Handler handler) {
        mOutHandler = handler;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        DisplayMetrics mDisplayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        Intent intent = getIntent();
        if (intent != null) {
            ID = intent.getIntExtra("ID", 0);
        }
        setContentView(R.layout.finger_print);
        mPass = (Button) findViewById(R.id.fp_pass);
        mFail = (Button) findViewById(R.id.fp_fail);
        mReset = (Button) findViewById(R.id.fp_reset);
        mPass.setOnClickListener(this);
        mFail.setOnClickListener(this);
        mReset.setOnClickListener(this);
        buttonShow(false,false,false);

        if (mOutHandler != null) {
            Message msg = mOutHandler
                    .obtainMessage(FactoryTestMessage.MSG_OPEN_UI_OK);
            msg.arg1 = (int) ID;
            mOutHandler.sendMessage(msg);
        }
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TAG);
        mVibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        mFingerprintManager = (FingerprintManager) this.getSystemService(Context.FINGERPRINT_SERVICE);
        enrollRoundPrg = (RoundProgressBar) findViewById(R.id.enrollPrg_roundProgressBar);
    }

    private void startFingerPrintTest() {
        clearEnrolledFingerPrint();
        enrollStart();
    }

    private void enrollStart() {//check device functional well or not
        if (mFingerprintManager.isHardwareDetected()) {
            Toast.makeText(this, "has fingerprint device", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "no fingerprint device", Toast.LENGTH_SHORT).show();
        }
        mEnrollmentCancel = new CancellationSignal();
        mFingerprintManager.enroll(mToken, mEnrollmentCancel, 0, mEnrollmentCallback);
        mEnrolling = true;
    }

    private void doVerified(int flag) {
        mFingerprintManager.authenticate(null, null, flag, mAuthenticationCallback, null);
        long mid = mFingerprintManager.getAuthenticatorId();
        Log.d(TAG, "mid = " + mid);
    }

    private void clearEnrolledFingerPrint() {//clear all fingerprints when in & out our test
        final List items = mFingerprintManager.getEnrolledFingerprints();
        if (items.size() > 0) {
            Log.d(TAG, "Fingerprint = " + items.size());
            for (Fingerprint i : items) {
                mFingerprintManager.remove(i, mRemovalCallback);
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        startFingerPrintTest();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mWakeLock.acquire();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mWakeLock.release();
        clearEnrolledFingerPrint();
    }

    public void onClick(View v) {
        int msg_id = 0;
        if (v == mPass) {
            pass = 1;
            mResult = "FingerPrint Test Pass";
            buttonShow(false,false,false);
            msg_id = FactoryTestMessage.MSG_ITEM_TEST_OK;
            sendMessage(msg_id);
            finish();
        } else if (v == mFail) {
            pass = 2;
            mResult = "FingerPrint Test Fail";
            if (FactoryItemManager.isSingleTest()) {
                msg_id = FactoryTestMessage.MSG_ITEM_TEST_OK;
                sendMessage(msg_id);
                finish();
            }
        } else if (v == mReset) {
            buttonShow(false,false,false);
            if (FactoryItemManager.getItemResetTime(ID) >= 5){// five times reset
                Toast.makeText(this, R.string.reset_times, Toast.LENGTH_LONG).show();
            } else {
                mResult = "reset";
                sendMessage(FactoryTestMessage.MSG_ITEM_TEST_RESET);
                setDialogProgress(0);
                enrollRoundPrg.doBeginEnrollAnimation();
                startFingerPrintTest();
            }
        }

    }

    private void sendMessage(int msg_id) {//send test result
        Message msg = mOutHandler.obtainMessage(msg_id);
        msg.arg1 = (int) ID;
        msg.arg2 = (int) pass;
        msg.obj = (String) mResult;
        mOutHandler.sendMessage(msg);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //back button or not
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((FactoryItemManager.isSingleTest())
                    || (FactoryItemManager.getItemResetTime(ID) >= 5)) {
                Log.d(TAG, " onKeyDown: back key is pressed");
                pass = 0;
                sendMessage(FactoryTestMessage.MSG_ITEM_TEST_OK);
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void buttonShow(boolean passBt,boolean resetBt,boolean failBt){
        mPass.setEnabled(passBt);
        mReset.setEnabled(resetBt);
        mFail.setEnabled(failBt);
    }

    private void setDialogProgress(int progress) {//update progress bar when enrolling
        if (progress >= 0 && progress <= 100) {
            enrollRoundPrg.setProgress(progress);
            if (progress == 100) {
                enrollRoundPrg.doEnrollSuccessAnimation();
            }
        }
    }

    private FingerprintManager.EnrollmentCallback mEnrollmentCallback
            = new FingerprintManager.EnrollmentCallback() {

        @Override
        public void onEnrollmentProgress(int remaining) {//must enroll 14 times & i don't know why
            Log.d(TAG,"onEnrollmentProgress  remaining = " + remaining);
            if (0 == remaining) {
                setDialogProgress(100);
                doVerified(0);//enroll completed and start match
            } else {
                setDialogProgress((14 - remaining) * 7);//update progressbar while enrolling
            }
        }

        @Override
        public void onEnrollmentHelp(int helpMsgId, CharSequence helpString) {
            Log.d(TAG,"onEnrollmentHelp  helpMsgId = " + helpMsgId + "	helpString = " + helpString);
        }

        @Override
        public void onEnrollmentError(int errMsgId, CharSequence errString) {
            Log.d(TAG,"onEnrollmentError  errMsgId = " + errMsgId + "	errString = " + errString);
            if (errMsgId == 7) {//match fail,it will lockout for some time maybe 30s
                enrollRoundPrg.doIdentifyFailAnimation();
                buttonShow(false,true,true);
                mFingerprintManager.resetTimeout(mToken); //Reset the lockout timer when asked to do so
            }
        }
    };

    private FingerprintManager.AuthenticationCallback mAuthenticationCallback
            = new FingerprintManager.AuthenticationCallback() {

        public void onAuthenticationError(int errorCode, CharSequence errString) { 
            Log.d(TAG,"onAuthenticationError");
        }

        public void onAuthenticationHelp(int helpCode, CharSequence helpString) { }

        public void onAuthenticationSucceeded(AuthenticationResult result) {
            Log.d(TAG,"onAuthenticationSucceeded");
            enrollRoundPrg.doIdentifySuccessAnimation();//match success
            buttonShow(true,true,true);
        }

        public void onAuthenticationFailed() {
            Log.d(TAG,"onAuthenticationFailed");
        }

        public void onAuthenticationAcquired(int acquireInfo) {}
    };

    private FingerprintManager.RemovalCallback mRemovalCallback
            = new FingerprintManager.RemovalCallback() {
        public void onRemovalError(Fingerprint fp, int errMsgId, CharSequence errString) { }

        public void onRemovalSucceeded(Fingerprint fingerprint) {
            Log.d(TAG,"onRemovalSucceeded");
        }
    };
}


另外注意上面使用到了几个权限需要加上

    
    
    

实现的功能比较简单,但指纹的基本功能都在里面,callback里面的状态比较多,都有Log打印出来的,关注你需要的就好了


原创文章,转载请说明出处,谢谢!

你可能感兴趣的:(Android)