postDelayed(Runnable r, long delayMillis)线程问题

本文介绍了Handler机制在不同线程中的应用方式。当在UI线程创建Handler时,需要注意避免在runnable中执行耗时操作,以防触发主线程异常。若在子线程中使用Handler,则需通过Looper.prepare()和Looper.loop()来准备Looper。
Handler调用postDelayed()时,runnable和Handler同处于一个线程,该线程为创建Handler的线程。如果在Handler是在UI线程充创建,则在runnable中不能执行网络请求等耗时操作,否则会报NetworkOnMainThreadException异常。如果要在子线程中创建Handler,需要在方法开始和结束分别使用Looper.prepare()和Looper.loop().
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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值