1. 程式人生 > >handle實現獲取簡訊驗證的工具

handle實現獲取簡訊驗證的工具

public class SendSmsTools {
    private int count ;
    public static final int MSG_CODE = 10;
    private TextView tv;
    private int myCount;
    private String hint="重新獲取";
    private int id;
    Context context;

    public SendSmsTools(int count, TextView tv, String hint, int id,Context context) {
        this.count = count;
        this.tv = tv;
        this.hint = hint;
        this.id = id;
        myCount=count;
        this.context=context;

    }

    public Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case MSG_CODE:
                    if (count<0){
                        handler.removeMessages(MSG_CODE);
                        if (tv!=null){
                            tv.setEnabled(true);
                            tv.setText(hint);
                        }
                    }else {
                        tv.setEnabled(false);

                        if (TextUtils.isEmpty(context.getResources().getString(id))){
                            tv.setText(count+"");
                        }else {
                            tv.setText(context.getResources().getString(id,count));
                        }
                        count--;

                        handler.sendEmptyMessageDelayed(MSG_CODE,1000);
                    }
                    break;
            }
        }
    };
    public void start() {
        count=myCount;
        handler.sendEmptyMessage(MSG_CODE);
    }
}

這是一個獲取的工具類。使用如下:

public class MainActivity extends AppCompatActivity {
    TextView sms;
    SendSmsTools tools;
    Handler handle;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sms= (TextView) findViewById(R.id.sms);
        tools=new SendSmsTools(10,sms,"重新獲取",R.string.send,this);
        handle=tools.handler;
        sms.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tools.start();
            }
        });
    }
}

以後要是使用驗證碼功能,幾行程式碼就搞定了。大家有什麼