一、前言:
公司项目是一款社交类聊天产品,为减轻后台压力,前端聊天发送的时候需要限制发送的频率。当频率过高,后台会推送限制再次发送的间隔(秒)。
下面是简单的倒计时的实现,与验证码功能一样。
二、具体代码:
/**限制频繁刷屏,倒计时
* @param mContext
* @param second
* @param pop_send
* @param send
* @param pop_edit_text
*/
public static void limitSend(Context mContext,int second, Button pop_send, Button send, EditText pop_edit_text) {
new TimeCount(second, 1000, mContext, pop_send, send, pop_edit_text).start();
}
//倒计时的计时器
static class TimeCount extends CountDownTimer {
private Context mContext;
private Button pop_send;
private Button send;
private EditText pop_edit_text;
public TimeCount(long millisInFuture, long countDownInterval, Context mContext, Button pop_send, Button send, EditText pop_edit_text) {
super(millisInFuture, countDownInterval);
this.mContext = mContext;
this.pop_send = pop_send;
this.send = send;
this.pop_edit_text = pop_edit_text;
}
@Override
public void onTick(long millisUntilFinished) {
<span style="white-space:pre"> </span>// 开始倒计时-->发送按钮不可点击,键盘的发送按钮设置无响应
pop_send.setClickable(false);
send.setClickable(false);
pop_edit_text.setImeOptions(EditorInfo.IME_ACTION_NONE);
<span style="white-space:pre"> </span>// 下面是按钮背景图的改变,(变暗),然后 显示倒计时的秒数
pop_send.setBackgroundResource(R.drawable.limit_send_bg);
send.setBackgroundResource(R.drawable.limit_send_bg);
pop_send.setTextColor(mContext.getResources().getColor(R.color.app_white));
send.setTextColor(mContext.getResources().getColor(R.color.app_white));
pop_send.setText(millisUntilFinished / 1000 + "秒");
send.setText(millisUntilFinished / 1000 + "秒");
}
@Override
public void onFinish() {
<span style="white-space:pre"> </span>//倒计时结束,按钮可点击,背景设置恢复正常状态
pop_send.setClickable(true);
send.setClickable(true);
pop_edit_text.setImeOptions(EditorInfo.IME_ACTION_SEND);
send.setBackgroundResource(R.drawable.notification_btn_bg);
pop_send.setBackgroundResource(R.drawable.notification_btn_bg);
pop_send.setTextColor(mContext.getResources().getColor(R.color.app_white));
send.setTextColor(mContext.getResources().getColor(R.color.app_white));
pop_send.setText("发射");
send.setText("发射");
}
}