android.os.CountDownTimer
public abstract class CountDownTimer {/** * Millis since epoch when alarm should stop:定时时间 */private final long mMillisInFuture;/** * The interval in millis that the user receives callbacks:回调间隔时间 */private final long mCountdownInterval; public CountDownTimer(long millisInFuture, long countDownInterval) { mMillisInFuture = millisInFuture; mCountdownInterval = countDownInterval;}
具体代码:
public class MainActivity extends AppCompatActivity {private TimeCount timeCount;private Button button;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.btn); timeCount = new TimeCount(11000,1000); timeCount.setCountListener(new TimeCount.CountListener() { @Override public void onTick(Long time) { button.setText(String.valueOf(time/1000).concat("s")); button.setEnabled(false);//设置不可点击 } @Override public void onFinish() { button.setText("重新发送"); button.setEnabled(true); } });}public void click(View view){ Toast.makeText(MainActivity.this,"click",Toast.LENGTH_SHORT).show(); timeCount.start();}
}
class TimeCount extends CountDownTimer {
private CountListener countListener; /** * @param millisInFuture The number of millis in the future from the call * to {@link #start()} until the countdown is done and {@link #onFinish()} * is called. * @param countDownInterval The interval along the way to receive * {@link #onTick(long)} callbacks. */ public TimeCount(long millisInFuture, long countDownInterval) { super(millisInFuture, countDownInterval); } @Override public void onTick(long millisUntilFinished) { countListener.onTick(millisUntilFinished); } @Override public void onFinish() { countListener.onFinish(); }public void setCountListener(CountListener countListener){ this.countListener = countListener;}public interface CountListener{ public void onTick(Long time); public void onFinish();}
}