之前我写过一篇博客使用极验实现验证功能,但是这个极验是需要通过公司进行审核才能通过的,那如果你要个人开发这种功能怎么实现?下面我叫大家实现。
1.导入github库,这个库是显示拼图界面的
implementation 'com.luozm.captcha:captcha:1.1.2'
2.导入popwindow框架:因为我们需要在界面上悬浮一个window而不是在另一个activity进行拼图界面的显示,当然你也可以用dialogfragment,但是这个方便点
implementation 'com.lxj:xpopup:1.8.7'
3.自定义custompop:
/**
* liwenpeng
* 2019/10/9 15:21
* AFun
* Descrobe:滑块验证
*/
public class HuaKuaiWindow extends CenterPopupView {
private Captcha captcha;
private Context mContext;
public HuaKuaiWindow(@NonNull Context context) {
super(context);
mContext = context;
}
// 返回自定义弹窗的布局
@Override
protected int getImplLayoutId() {
return R.layout.layout_huakuaiwindow;
}
// 执行初始化操作,比如:findView,设置点击,或者任何你弹窗内的业务逻辑
@Override
protected void onCreate() {
super.onCreate();
captcha = (Captcha) findViewById(R.id.captCha);
captcha.setMaxFailedCount(10);
captcha.setCaptchaListener(new Captcha.CaptchaListener() {
@Override
public String onAccess(long time) {
Toast.makeText(mContext,"验证成功",Toast.LENGTH_SHORT).show();
dismiss();
return "验证通过,耗时"+time+"毫秒";
}
@Override
public String onFailed(int failedCount) {
Toast.makeText(mContext,"验证失败",Toast.LENGTH_SHORT).show();
return "验证失败,已失败"+failedCount+"次";
}
@Override
public String onMaxFailed() {
Toast.makeText(mContext,"验证超过次数,你的帐号被封锁",Toast.LENGTH_SHORT).show();
return "验证失败,帐号已封锁";
}
});
}
// 设置最大宽度,看需要而定
@Override
protected int getMaxWidth() {
return super.getMaxWidth();
}
// 设置最大高度,看需要而定
@Override
protected int getMaxHeight() {
return super.getMaxHeight();
}
// 设置自定义动画器,看需要而定
@Override
protected PopupAnimator getPopupAnimator() {
return super.getPopupAnimator();
}
/**
* 弹窗的宽度,用来动态设定当前弹窗的宽度,受getMaxWidth()限制
*
* @return
*/
protected int getPopupWidth() {
return 0;
}
/**
* 弹窗的高度,用来动态设定当前弹窗的高度,受getMaxHeight()限制
*
* @return
*/
protected int getPopupHeight() {
return 0;
}
}
验证成功的时候我们就把他关闭。
4.滑块的布局文件,注意图片可以本地选也可以网络
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.luozm.captcha.Captcha
android:id="@+id/captCha"
android:layout_centerInParent="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:src="@drawable/default_room"/>
</RelativeLayout>
5.在登录的时候进行展示:
public void onClick(View view) {
int id = view.getId();
if (id == R.id.btn_register){
startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
}else if (id == R.id.btn_login){
if (!isFIrstclickLogin){
toYanzheng();
}else {
toLogin();
}
}
}
/**
* 展示验证
* */
private void toYanzheng() {
new XPopup.Builder(this)
.asCustom(new HuaKuaiWindow(this))
.show();
isFIrstclickLogin = true;
}
第一次点击展示验证板块,验证完成直接登录就行。
涉及的github地址:
滑块:https://github.com/luozhanming/Captcha
xpop:https://github.com/li-xiaojun/XPopup