android-计时器离开页面继续用法

有时候用到倒计时的时候离开这个页面并不想结束这个倒计时,还需要继续运行,举一个场景,一个发验证码的一分钟倒计时,倒计时到30s的时候返回上一个页面,然后5s进去,在不改变任何属性的情况下,需要继续倒计时,从25s开始..

当然倒计时的方法有很多种,这里用到的Runnable+Handler实现

创建一个全局变量
public static int remainTime = 0;
创建一个专门每秒减1的计时器
public Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			remainTime--;
			if (remainTime > 0) {
			} else {
					reSendTip.setText("点击再次发送");
					reSendTip2.setVisibility(View.GONE);
					reSendTip.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							String timeString = reSendTip.getText().toString();
							try {
								Integer.valueOf(timeString);
							} catch (Exception e) {
								new GetCheckCodeTask(GetCheckCodeActivity.this,
										extend, patientId,
										getCheckCodeResultListener).execute();
								remainTime = 60;
								reSendTip.setText(remainTime + "");
								reSendTip2.setVisibility(View.VISIBLE);
								handler.postDelayed(runnable, 1000);
							}
						}
					});
				handler.removeCallbacks(runnable);
			}
		};
	};
private Runnable runnable = new Runnable() {
		public void run() {
				handler.obtainMessage(1).sendToTarget();
				handler.postDelayed(this, 1000);
		}
	};
创建一个每秒显示的线程
public Handler handler2 = new Handler() {
		public void handleMessage(android.os.Message msg) {
			reSendTip.setText(remainTime + "");
			if (remainTime > 0) {
			} else {
					reSendTip.setText("点击再次发送");
					reSendTip2.setVisibility(View.GONE);
					reSendTip.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							String timeString = reSendTip.getText().toString();
							try {
								Integer.valueOf(timeString);
							} catch (Exception e) {
								new GetCheckCodeTask(GetCheckCodeActivity.this,
										extend, patientId,
										getCheckCodeResultListener).execute();
								remainTime = 60;
								reSendTip.setText(remainTime + "");
								reSendTip2.setVisibility(View.VISIBLE);
								handler.postDelayed(runnable, 1000);
							}
						}
					});
				handler2.removeCallbacks(runnable2);
			}
		};
	};
private Runnable runnable2 = new Runnable() {
		public void run() {
				handler2.obtainMessage(1).sendToTarget();
				handler2.postDelayed(this, 1000);
		}
	};
开始的onCreate方法判断
if(remainTime <= 0){
			GetCheckCodeTask task = new GetCheckCodeTask(this, extend, patientId,
					getCheckCodeResultListener);
			task.execute();
			remainTime = 60;
			handler.postDelayed(runnable, 1000);
			handler.postDelayed(runnable2, 1000);
		}else{
			handler.postDelayed(runnable2, 1000);
		}

在返回是关闭显示的线程,再确认验证码通过后关闭2个线程
handler2.removeCallbacks(runnable2);
handler.removeCallbacks(runnable);






你可能感兴趣的:(Handler,Runnable,Android)