我们可以看下API的描述
public final boolean postDelayed(Runnable r, long delayMillis)
Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. The runnable will be run on the thread to which this handler is attached.
Parameters: r The Runnable that will be executed. delayMillis The delay (in milliseconds) until the Runnable will be executed.翻译为:
因为Runnable r 被加入了消息队列中,将会在被确定的时间消耗后执行。这个runnable将会被执行在handler联系的线程中。
参数:
r 这个将会被执行的Runnable
delayMillis 延迟的秒数指导Runnable被执行
使用方法
1.首先创建一个Handler对象
Handler handler = new Handler();
2.然后创建一个Runnable对象
Runnable runis=new Runnable() { @Override public void run() { isExit=false; } };3.调用postDelayed方法
handler.postDelayed(runis, 2000);
public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { Runnable runis=new Runnable() { @Override public void run() { isExit=false; } }; Handler handler = new Handler(); if (isExit) { finish(); } else { isExit = true; Toast.makeText(this, "连续点击退出应用", Toast.LENGTH_SHORT).show(); handler.postDelayed(runis, 2000); } return true; } }