android中postDelayed方法的讲解(连续两次点击退出)

我们可以看下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;
		}
		
	}


你可能感兴趣的:(android中postDelayed方法的讲解(连续两次点击退出))