如何在Android中实现验证码

时间:2013-07-30 04:30:45

标签: android captcha

我想在我的应用程序中进行验证码。经过初步分析,我发现大多数人都建议使用'Simplcaptcha'。我试了一下。但我的努力是徒劳的。 'simplecaptcha'的输出是一个AWT组件。所以它不能在Android中使用。有没有办法在Android中通过任何转换使用相同的,或者是否有任何其他好的库可用。如果是这样,任何人都可以指导我找到一份好文档或示例。这对我来说是一个很大的帮助。

2 个答案:

答案 0 :(得分:1)

您可以使用下面的自定义视图来显示captcha(根据您的需要进行调整,例如,如果您想拥有alphanumeric captcha,或者想要skewed captcha

public class CaptchaView extends ImageView {

private Paint mPaint;
private static String mCaptchaAsText;

public CaptchaView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
}

public CaptchaView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public CaptchaView(Context context) {
    super(context);
    init();
}

private void init() {
    mPaint = new Paint();
    mPaint.setColor(Color.BLACK);

    initCaptcha();
}

private static void initCaptcha() {
    mCaptchaAsText = "";
    for (int i = 0; i < 4; i++) {
        int number = (int) (Math.random() * 10);
        mCaptchaAsText += number;
    }
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int desiredWidth = 300;
    int desiredHeight = 80;

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    int width;
    int height;

    // Measure Width
    if (widthMode == MeasureSpec.EXACTLY) {
        // Must be this size
        width = widthSize;
    } else if (widthMode == MeasureSpec.AT_MOST) {
        // Can't be bigger than...
        width = Math.min(desiredWidth, widthSize);
    } else {
        // Be whatever you want
        width = desiredWidth;
    }

    // Measure Height
    if (heightMode == MeasureSpec.EXACTLY) {
        // Must be this size
        height = heightSize;
    } else if (heightMode == MeasureSpec.AT_MOST) {
        // Can't be bigger than...
        height = Math.min(desiredHeight, heightSize);
    } else {
        // Be whatever you want
        height = desiredHeight;
    }

    // MUST CALL THIS
    setMeasuredDimension(width, height);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    mPaint.setTextSize(getMeasuredHeight());
    canvas.drawText(mCaptchaAsText,
            ((canvas.getWidth() - mPaint.measureText(mCaptchaAsText)) / 2),
            getMeasuredHeight(), mPaint);
}

public static boolean match(String value) {
    if (value.equals(mCaptchaAsText)) {
        return true;
    } else {
        if (value != null && value.length() > 0)
            initCaptcha();

        return false;
    }
}
}

答案 1 :(得分:0)

Android应用程序的非常易于使用的最小选项,设备上的Captcha系统 REFER