在我们的开发中,有很多功能是不能放在我们的activity中进行,例如想从网络上下载什么东西,如果我们把此功能写在了activity中,就有可能导致我们下载过程中整个activity处于等待的状态,也有可能因为下载不下来,而使应用程序崩溃等问题。因此,为了保持良好的用户体验,任何长时间运行的任务都应该再单独的线程中。即将任务分配给单独的线程然后将结果返回给activity,这就是handler及其相关类的作用。
在sdk文档中,关于handler的用法是这样说的:
Class Overview
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.
而messageQueue则涉及到looper这个类。嗯.........先弄明白两个概念:
looper:一个线程可以产生一个looper对象,他可以用来处理线程的消息队列(messageQueue);
messageQueue:用来存放线程放入的消息;
而此时,构造一个handlre对象来与looper类沟通,将消息放入消息队列中,同时可以用来处理从消息队列中取出的消息。
而对于handler点的使用,我们可以先创建一个带无参数的构造函数的handler,handler就可以与当前运行线程的looper关联,而在实现handler时,我们必须提供handlerMessage(message msg)的方法,该方法其实就是允许我们传递消息的钩子。接下来,我们将要执行的操作写在线程对象的run方法中(至于使用线程方法,其一是继承Thread,另外一种方法则是实现runable接口),这里要注意的时,handler处理消息与使用该handler的activity是处在同一个线程的,因为他调用的是run函数,但没调用线程的Start()方法。这样后我们就可以调用handler的sendMessage方法将消息加入到有looper维护的messageQueue中。
简例1 :没有启动新线程的例子:
该例子就是当你点击开始按钮时,他将一个线程对象加入到消息队列中去,这时它调用他的run()函数,而在run函数中,则是执行每隔3妙把线程对象再加入到消息队列中,这样循环,直到你点击结束按钮才结束。
简例2:启动新线程:
其输出为:
The main thread id = 1
The worker thread id = 8
The handler thread id = 1
由此也可以看出:handler处理消息是与使用handler的activity是在同一个线程中的。