自定义控件及各种特效android中handler.pdf
前言
学习android一段时间了,为了进一步了解android的应用是如何设计开发的,决定详细研究几个开源的an
droid应用。从一些开源应用中吸收点东西,一边进行量的积累,一边探索android的学习研究方向。这里我首先
选择了jwood的StandupTimer项目。本文将把研究的内容笔记整理,建立一个索引列表。
Android.os.Handler涉及较多的知识点,我把一些列举在下面,将主要介绍Handler:
•android.os.Handler、android.os.Handler.Callback
•Looper、
•Threadle、Runnable
•Message、Messagequeue
android.os.Handler
Handler在android里负责发送和处理消息。它的主要用途有:
1)按发送消息或执行某个Runnanble(使用POST方法);
2)从其他线程中发送来的消息放入消息队列中,避免线程(常见于更新UI线程)
默认情况下,Handler接受的是当前线程下的消息循环实例(使用Handler(Looperlooper)、Handler(Lo
operlooper,Handler.Callbackcallback)可以指定线程),同时一个消息队列可以被当前线程中的多个对象进
行分发、处理(在UI线程中,系统已经有一个Activity来处理了,你可以再起若干个Handler来处理)。在实
例化Handler的时候,Looper可以是任意线程的,只要有Handler的指针,任何线程也都可以sendMessag
e。Handler对于Message的处理不是并发的。一个Looper只有处理完一条Message才会下一条,所以
消息的处理是阻塞形式的(handleMessage()方法里不应该有耗时操作,可以将耗时操作放在其他线程执行,操
作完后发送Message(通过sendMessges方法),然后由handleMessage()更新UI)。
倒计时程序
利用Timer编写一个倒计时程序,程序使用Timer和TimerTask来完成倒计时,同时使用sendMessages
方法发送消息,然后在HanleMessage里更新UI。
Activity布局:
Layout
?xmlversion=1.0encoding=utf-8?
LinearLayoutxmlns:android=
android:orientation=vertical
android:layout_width=fill_parent
android:layout_height=fill_parent
TextView
android:layout_width=fill_parent
android:layout_height=wrap_content
android:layout_gravity=center
android:id=@+id/txt
/
Button
android:id=@+id/btnStartTime
android:text=开始计时
android:layout_width=80dip
android:layout_height=wrap_content
/Button
Button
android:id=@+id/btnStopTime
android:text=停止计时
an