本文介绍一个Android手势密码开源库的使用及实现的详细过程,该开源库主要实现以下几个功能:
- 支持手势密码的绘制,并支持密码保存功能,解锁时自动比对密码给出结果
- 封装了绘制密码的方法,比对两次密码是否一致,可以快捷地进行手势密码的设置
- 可以设置密码输入错误后的重试次数上限
- 可以自定义不同状态下手势密码图案的颜色
- 可以自定义手势密码的触摸点数量(n*n)
最近需要用到手势密码解锁功能,找了一些demo感觉用起来都有点麻烦,于是参考一些文章自己造了下轮子,封装了相关的一些方法,使用起来比较便捷。
github链接如下,觉得还可以请帮忙star支持下~
github链接 https://github.com/autume/GestureLock
个人博客 http://blog.csdn.net/yaodong379
首先看下使用效果:
"@+id/gesturelock"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:preference_id="1"
android:layout_marginTop="30dp"
app:count="3" />
可以设置的一些参数,说明如下:
color_no_finger:未触摸时圆形的颜色
color_finger_on:触摸时圆形的颜色
color_finger_up_correct:输入正确时圆形的颜色
color_finger_up_error:出错时圆形的颜色
count:收拾密码的圆形数量,n*n
preference_id:手势密码保存的id号,不输入或输入-1则使用默认的id
private void initGesture() {
mGestureLockViewGroup = (GestureLockViewGroup) findViewById(R.id.gesturelock);
gestureEventListener();
gesturePasswordSettingListener();
gestureRetryLimitListener();
}
private void gestureEventListener() {
mGestureLockViewGroup.setGestureEventListener(new GestureEventListener() {
@Override
public void onGestureEvent(boolean matched) {
mylog.d("onGestureEvent matched: " + matched);
if (!matched) {
tv_state.setTextColor(Color.RED);
tv_state.setText("手势密码错误");
} else {
if (isReset) {
isReset = false;
Toast.makeText(MainActivity.this, "清除成功!", Toast.LENGTH_SHORT).show();
resetGesturePattern();
} else {
tv_state.setTextColor(Color.WHITE);
tv_state.setText("手势密码正确");
}
}
}
});
}
若已经设置有密码则会进入该回调,在这里对结果进行处理,上面的例子中加入了一个重设密码的处理。
private void gesturePasswordSettingListener() {
mGestureLockViewGroup.setGesturePasswordSettingListener(new GesturePasswordSettingListener() {
@Override
public boolean onFirstInputComplete(int len) {
if (len > 3) {
tv_state.setTextColor(Color.WHITE);
tv_state.setText("再次绘制手势密码");
return true;
} else {
tv_state.setTextColor(Color.RED);
tv_state.setText("最少连接4个点,请重新输入!");
return false;
}
}
@Override
public void onSuccess() {
tv_state.setTextColor(Color.WHITE);
Toast.makeText(MainActivity.this, "密码设置成功!", Toast.LENGTH_SHORT).show();
tv_state.setText("请输入手势密码解锁!");
}
@Override
public void onFail() {
tv_state.setTextColor(Color.RED);
tv_state.setText("与上一次绘制不一致,请重新绘制");
}
});
}
若还未设置密码,绘制手势的时候会进入该回调,返回值为绘制的触摸点的数量,onFirstInputComplete中返回true则进入第二手势密码的绘制,两次输入一致后自动保存密码。
private void gestureRetryLimitListener() {
mGestureLockViewGroup.setGestureUnmatchedExceedListener(3, new GestureUnmatchedExceedListener() {
@Override
public void onUnmatchedExceedBoundary() {
tv_state.setTextColor(Color.RED);
tv_state.setText("错误次数过多,请稍后再试!");
}
});
}
若设置了该监听事件,则输入错误有次数限制,超过上限后进入回调,在该回调中进行处理。
清除密码的逻辑自己加个判断处理下即可,具体可以看下github上的demo
public void removePassword() :清除密码
public void savePassword() : 保存密码,设置手势密码成功后会自动保存,也可以调用该接口另外设置密码
public void getPassword(): 获取密码
public void setRetryTimes(int retryTimes) : 设置重试次数上限
public boolean isSetPassword() : 返回现在是否已经设置有密码
public void resetView() : 将视图Reset
仅需加入两行代码:
在工程的 build.gradle中加入:
allprojects {
repositories {
...
maven { url "https://jitpack.io" }
}
}
module的build.gradle中加入依赖:
dependencies {
compile 'com.github.autume:GestureLock:1.0.0'
}
总的使用就是这样,是不是很简单!
下面讲下实现的过程,如果只是直接拿来用的话也可以略过这部分。
这部分主要参考Hongyang大大的博客,稍微修改了一下
public GestureLockView(Context context, int colorNoFingerr, int colorFingerOn, int colorCorrect, int colorError) {
super(context);
this.mColorNoFinger = colorNoFingerr;
this.mColorFingerOn = colorFingerOn;
this.mColorFingerUpCorrect = colorCorrect;
this.mColorFingerUpError = colorError;
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mArrowPath = new Path();
}
@Override
protected void onDraw(Canvas canvas) {
switch (mCurrentStatus) {
case STATUS_FINGER_ON:
// 绘制外圆
mPaint.setStyle(Style.STROKE);
mPaint.setColor(mColorFingerOn);
mPaint.setStrokeWidth(2);
canvas.drawCircle(mCenterX, mCenterY, mRadius, mPaint);
// 绘制内圆
mPaint.setStyle(Style.FILL);
canvas.drawCircle(mCenterX, mCenterY, mRadius * mInnerCircleRadiusRate, mPaint);
break;
case STATUS_FINGER_UP:
// 绘制外圆
if (GestureLockViewGroup.isCorrect)
mPaint.setColor(mColorFingerUpCorrect);
else
mPaint.setColor(mColorFingerUpError);
mPaint.setStyle(Style.STROKE);
mPaint.setStrokeWidth(2);
canvas.drawCircle(mCenterX, mCenterY, mRadius, mPaint);
// 绘制内圆
mPaint.setStyle(Style.FILL);
canvas.drawCircle(mCenterX, mCenterY, mRadius * mInnerCircleRadiusRate, mPaint);
drawArrow(canvas);
break;
case STATUS_NO_FINGER:
// 绘制外圆
mPaint.setStyle(Style.STROKE);
mPaint.setColor(mColorNoFinger);
canvas.drawCircle(mCenterX, mCenterY, mRadius, mPaint);
// 绘制内圆
mPaint.setStyle(Style.FILL);
mPaint.setColor(mColorNoFinger);
canvas.drawCircle(mCenterX, mCenterY, mRadius * mInnerCircleRadiusRate, mPaint);
break;
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mWidth = MeasureSpec.getSize(widthMeasureSpec);
mHeight = MeasureSpec.getSize(heightMeasureSpec);
// 取长和宽中的小值
mWidth = mWidth < mHeight ? mWidth : mHeight;
mRadius = mCenterX = mCenterY = mWidth / 2;
mRadius -= mStrokeWidth / 2;
// 绘制三角形,初始时是个默认箭头朝上的一个等腰三角形,用户绘制结束后,根据由两个GestureLockView决定需要旋转多少度
float mArrowLength = mWidth / 2 * mArrowRate;
mArrowPath.moveTo(mWidth / 2, mStrokeWidth + 2);
mArrowPath.lineTo(mWidth / 2 - mArrowLength, mStrokeWidth + 2 + mArrowLength);
mArrowPath.lineTo(mWidth / 2 + mArrowLength, mStrokeWidth + 2 + mArrowLength);
mArrowPath.close();
mArrowPath.setFillType(Path.FillType.WINDING);
}
private void drawArrow(Canvas canvas) {
if (mArrowDegree != -1) {
mPaint.setStyle(Paint.Style.FILL);
canvas.save();
canvas.rotate(mArrowDegree, mCenterX, mCenterY);
canvas.drawPath(mArrowPath, mPaint);
canvas.restore();
}
}
"1.0" encoding="utf-8"?>
"color_no_finger" format="color" />
"color_finger_on" format="color" />
"color_finger_up_correct" format="color" />
"color_finger_up_error" format="color" />
"count" format="integer" />
"preference_id" format="integer" />
"GestureLockViewGroup">
"color_no_finger" />
"color_finger_on" />
"color_finger_up_correct" />
"color_finger_up_error" />
"count" />
"preference_id" />
public GestureLockViewGroup(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
/**
* 获得所有自定义的参数的值
*/
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.GestureLockViewGroup, defStyle, 0);
mNoFingerColor = a.getColor(R.styleable.GestureLockViewGroup_color_no_finger, mNoFingerColor);
mFingerOnColor = a.getColor(R.styleable.GestureLockViewGroup_color_finger_on, mFingerOnColor);
mFingerUpColorCorrect = a.getColor(R.styleable.GestureLockViewGroup_color_finger_up_correct, mFingerUpColorCorrect);
mFingerUpColorError = a.getColor(R.styleable.GestureLockViewGroup_color_finger_up_error, mFingerUpColorError);
mCount = a.getInt(R.styleable.GestureLockViewGroup_count, mCount);
mPrferenceId = a.getInt(R.styleable.GestureLockViewGroup_preference_id, mPrferenceId);
a.recycle();
/**
* 获取密码状态
*/
gesturePreference = new GesturePreference(context, mPrferenceId);
password = gesturePreference.ReadStringPreference();
Log.d(TAG, "password now is : " + password);
isSetPassword = !password.equals("null"); //判断是否已经保存有密码
isInPasswordSettingMode = !isSetPassword; //当未设置密码,进入密码设置模式
// 初始化画笔
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPath = new Path();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
int x = (int) event.getX();
int y = (int) event.getY();
Log.d(TAG, "mTryTimes : " + mTryTimes);
//重试次数超过限制,直接返回
if (mTryTimes <= 0 && isRetryTimeLimit) {
return true;
}
switch (action) {
case MotionEvent.ACTION_DOWN:
reset(); // 重置
break;
case MotionEvent.ACTION_MOVE:
drawAndGetSelectedWhenTouchMove(x, y);
break;
case MotionEvent.ACTION_UP:
if (isInPasswordSettingMode) {
if (gesturePasswordSettingListener != null)
setPasswordHandle(); //设置密码
} else {
if (mChoose.size() > 0) {
isCorrect = checkAnswer();
} else {
return true;
}
if (gestureEventListener != null) {
gestureEventListener.onGestureEvent(isCorrect); //将结果回调
}
if (this.mTryTimes == 0) {
gestureUnmatchedExceedListener.onUnmatchedExceedBoundary(); //超出重试次数,进入回调
}
}
drawWhenTouchUp();
break;
}
invalidate();
return true;
}
private void drawAndGetSelectedWhenTouchMove(int x, int y) {
mPaint.setColor(mFingerOnColor);
mPaint.setAlpha(50);
GestureLockView child = getChildIdByPos(x, y);
if (child != null) {
int cId = child.getId();
if (!mChoose.contains(cId)) {
mChoose.add(cId);
mChooseString = mChooseString + cId;
child.setMode(Mode.STATUS_FINGER_ON);
// 设置指引线的起点
mLastPathX = child.getLeft() / 2 + child.getRight() / 2;
mLastPathY = child.getTop() / 2 + child.getBottom() / 2;
if (mChoose.size() == 1)// 当前添加为第一个
{
mPath.moveTo(mLastPathX, mLastPathY);
} else
// 非第一个,将两者使用线连上
{
mPath.lineTo(mLastPathX, mLastPathY);
}
}
}
// 指引线的终点
mTmpTarget.x = x;
mTmpTarget.y = y;
}
private void drawWhenTouchUp() {
if (isCorrect) {
mPaint.setColor(mFingerUpColorCorrect);
} else {
mPaint.setColor(mFingerUpColorError);
}
mPaint.setAlpha(50);
Log.d(TAG, "mChoose = " + mChoose);
// 将终点设置位置为起点,即取消指引线
mTmpTarget.x = mLastPathX;
mTmpTarget.y = mLastPathY;
// 改变子元素的状态为UP
setItemModeUp();
// 计算每个元素中箭头需要旋转的角度
for (int i = 0; i + 1 < mChoose.size(); i++) {
int childId = mChoose.get(i);
int nextChildId = mChoose.get(i + 1);
GestureLockView startChild = (GestureLockView) findViewById(childId);
GestureLockView nextChild = (GestureLockView) findViewById(nextChildId);
int dx = nextChild.getLeft() - startChild.getLeft();
int dy = nextChild.getTop() - startChild.getTop();
// 计算角度
int angle = (int) Math.toDegrees(Math.atan2(dy, dx)) + 90;
startChild.setArrowDegree(angle);
}
}
设置密码处理:
private void setPasswordHandle() {
if (isWaitForFirstInput) {
if (gesturePasswordSettingListener.onFirstInputComplete(mChooseString.length())) {
firstInputPassword = mChooseString;
isWaitForFirstInput = false;
}
} else {
if (firstInputPassword.equals(mChooseString)) {
gesturePasswordSettingListener.onSuccess();
savePassword(mChooseString);
isInPasswordSettingMode = false;
} else {
gesturePasswordSettingListener.onFail();
}
}
reset();
}
检查手势密码是否正确:
public boolean checkAnswer() {
if (password.equals(mChooseString)) {
return true;
} else {
if (isRetryTimeLimit)
this.mTryTimes--;
return false;
}
}
重置:
private void reset() {
mChoose.clear();
mChooseString = "";
mPath.reset();
for (GestureLockView gestureLockView : mGestureLockViews) {
gestureLockView.setMode(Mode.STATUS_NO_FINGER);
gestureLockView.setArrowDegree(-1);
}
}
public void setGestureEventListener(GestureEventListener gestureEventListener) {
this.gestureEventListener = gestureEventListener;
}
public void setGestureUnmatchedExceedListener(int retryTimes, GestureUnmatchedExceedListener gestureUnmatchedExceedListener) {
isRetryTimeLimit = true;
this.mTryTimes = retryTimes;
this.gestureUnmatchedExceedListener = gestureUnmatchedExceedListener;
}
public void setGesturePasswordSettingListener(GesturePasswordSettingListener gesturePasswordSettingListener) {
this.gesturePasswordSettingListener = gesturePasswordSettingListener;
}
public void removePassword() {
gesturePreference.WriteStringPreference("null");
this.isSetPassword = false;
isWaitForFirstInput = true;
isInPasswordSettingMode = true;
}
public void savePassword(String password) {
this.password = password;
gesturePreference.WriteStringPreference(password);
}
public String getPassword() {
return password;
}
public void resetView() {
reset();
invalidate();
}
public void setRetryTimes(int retryTimes) {
this.mTryTimes = retryTimes;
}
public boolean isSetPassword() {
return isSetPassword;
}
就是简单的存和读
public GesturePreference(Context context, int nameTableId) {
this.context = context;
if (nameTableId != -1)
this.nameTable = nameTable + nameTableId;
}
public void WriteStringPreference(String data) {
SharedPreferences preferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(nameTable, data);
editor.commit();
}
public String ReadStringPreference() {
SharedPreferences preferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
return preferences.getString(nameTable, "null");
}
ok,至此,整个手势密码的实现就完成了。
本文首发地址:http://www.codeceo.com/article/android-gusture-lock.html