今天学习了Handler和HandlerThread
现在脑子里对他们的概念还比较模糊,贴上它们在SDK上的解释吧
Handler:
A Handler allows you to send and process Message
and Runnable objects associated with a thread's MessageQueue
. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
There are two main uses for a Handler:
(1) to schedule messages and runnables to be executed as some point in the future;
and (2) to enqueue an action to be performed on a different thread than your own.
HandlerThread:
Handy class for starting a new thread that has a looper. The looper can then be used to create handler classes. Note that start() must still be called.
唉 翻译到第一句就悲剧了,长句子,找了个朋友帮忙翻译是这样的:
一个Handler允许你发送和处理联系一个线程信息队列的信息和线程对象。
剩下的不翻了,恶补语法去……
通过循环来实现进度条的读取,我以为简单的通过for(;;)循环就可以实现
事实上完全不是这样。android的进度条实现是通过Handler和联系他的线程之间来回的通信,完成这一过程的。
具体代码不贴了。我想到了一个很形象有趣的比喻:
这个过程就像和狗狗玩掷飞盘的游戏一样,
Handler启动线程(主人把飞盘抛出),
进程运行后,又把修正过的信息发回给Handle(狗狗把飞盘叼回来,恩,顺带还狠狠的咬了飞盘一口),
然后Handler继续抛出,如此循环,
直到达到了某个条件(狗狗把飞盘咬坏咯,狗狗好委屈),
那么循环就停止。