当前位置 : 主页 > 编程语言 > c++ >

短信验证码计时工具

来源:互联网 收集:自由互联 发布时间:2021-06-30
一个短信验证码计时工具 实现了button的文字显示以及enable的改变,其中缓存工具用的是ACache,可以随意替换 public class CodeTimeUtil { private final String SMS_CODE_KEY = "smsCodeKey"; private int second;
一个短信验证码计时工具 实现了button的文字显示以及enable的改变,其中缓存工具用的是ACache,可以随意替换
public class CodeTimeUtil {


    private  final String SMS_CODE_KEY = "smsCodeKey";
    private int second;
    private Timer timer;
    private TimerTask timerTask;
    private Handler handler;

    private static CodeTimeUtil instance;

    public static CodeTimeUtil getInstance(){
        if (instance == null)
            instance = new CodeTimeUtil();

        return instance;
    }

    private CodeTimeUtil() {
    }

    public  void startSmsCode(final Button view, boolean isStartNow){

         handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if (view == null){
                    return;
                }
                view.setText("已发送("+msg.what+"秒)");
                if (msg.what > 0) {
                    view.setEnabled(false);

                } else {
                    view.setEnabled(true);
                    view.setText("获取短信验证码");
                }

            }
        };

        try {
            long cacheTime =   Long.parseLong(ACache.get(App.INSTANCE).getAsString(SMS_CODE_KEY));
            if (cacheTime != 0 && System.currentTimeMillis() - cacheTime < 60*1000 ){
                startTime((int) (60 - ((System.currentTimeMillis() - cacheTime) /1000)));
                return;
            }
        }catch (Exception e){
            Log.e("CodeTime","code Timer error");
        }



        if (isStartNow) {
            ACache.get(App.INSTANCE).put(SMS_CODE_KEY, System.currentTimeMillis() + "");
            if (view != null)
                startTime(60);
        }


    }




    private  void startTime(int s){
        stopTimer();
        second = s;
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                if (second == 0) {
                    cancel();
                    return;
                }
                second--;
                handler.sendEmptyMessage(second);
            }
        };
        timer.schedule(timerTask,0,1000);

    }


    public void stopTimer(){
        if (timer != null) {
            timerTask = null;
            timer.cancel();
        }
    }


    public void removeCacheTime(){
        if (  ACache.get(App.INSTANCE).getAsString(SMS_CODE_KEY) != null)
            ACache.get(App.INSTANCE).remove(SMS_CODE_KEY);
        stopTimer();

    }

}
网友评论