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;
		}
		
	}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值