postDelayed(Runnable runnable ,long delayMillis)只执行一次

本文详细介绍了如何使用Handler的postDelayed方法来执行定时任务。包括如何设置一次性定时任务及循环定时任务,并提供了停止定时任务的方法。

postDelayed(Runnable runnable ,long delayMillis)方法含义,隔delayMillis的时间后去执行一次runable(不循环,只有一次)


  1. 如果想要关闭此定时器,可以这样操作  
  2. handler.removeCallbacks(runnable);

若要循环的执行,就是每隔2s去执行一次线程,就用递归,在run()中执行

  1. Runnable runnable=new Runnable(){  
  2.    @Override  
  3.    public void run() {  
  4.     // TODO Auto-generated method stub  
  5.     //要做的事情,这里再次调用此Runnable对象,以实现每两秒实现一次的定时器操作  
  6.     handler.postDelayed(this, 2000);  
  7.    }     
  8. };  
  9. handler.postDelayed(this, 2000);

若得到自己想要的数据后要停止该定时器的发送,有两种方法

1:在run()中定义一个标志位,

loop_send
run(){
	if(loop_send){
}
}
2:removeCallbacks()方法

public final boolean postDelayed(@NonNull Runnable r, long delayMillis) { 537 return sendMessageDelayed(getPostMessage(r), delayMillis); 538 } 539 540 /** @hide */ 541 public final boolean postDelayed(Runnable r, int what, long delayMillis) { 542 return sendMessageDelayed(getPostMessage(r).setWhat(what), delayMillis); 543 } 544 545 /** 546 * Causes the Runnable r to be added to the message queue, to be run 547 * after the specified amount of time elapses. 548 * The runnable will be run on the thread to which this handler 549 * is attached. 550 * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b> 551 * Time spent in deep sleep will add an additional delay to execution. 552 * 553 * @param r The Runnable that will be executed. 554 * @param token An instance which can be used to cancel {@code r} via 555 * {@link #removeCallbacksAndMessages}. 556 * @param delayMillis The delay (in milliseconds) until the Runnable 557 * will be executed. 558 * 559 * @return Returns true if the Runnable was successfully placed in to the 560 * message queue. Returns false on failure, usually because the 561 * looper processing the message queue is exiting. Note that a 562 * result of true does not mean the Runnable will be processed -- 563 * if the looper is quit before the delivery time of the message 564 * occurs then the message will be dropped. 565 */ 566 public final boolean postDelayed( 567 @NonNull Runnable r, @Nullable Object token, long delayMillis) { 568 return sendMessageDelayed(getPostMessage(r, token), delayMillis); 569 }解释一下这三个方法
最新发布
11-27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值