Android之Handler消息機制
Android中Handle類(lèi)的主要作用:
本文引用地址:http://dyxdggzs.com/article/201610/306009.htm1.在新啟動(dòng)的線(xiàn)程中發(fā)送給消息
2.在主線(xiàn)程獲取、處理消息
為什么要用Handle這樣的一個(gè)機制:
因為在A(yíng)ndroid系統中UI操作并不是線(xiàn)程安全的,如果多個(gè)線(xiàn)程并發(fā)的去操作同一個(gè)組件,可能導致線(xiàn)程安全問(wèn)題。為了解決這一個(gè)問(wèn)題,android制定了一條規則:只允許UI線(xiàn)程來(lái)修改UI組件的屬性等,也就是說(shuō)必須單線(xiàn)程模型,這樣導致如果在UI界面進(jìn)行一個(gè)耗時(shí)叫長(cháng)的數據更新等就會(huì )形成程序假死現象 也就是ANR異常,如果20秒中沒(méi)有完成程序就會(huì )強制關(guān)閉。所以比如另一個(gè)線(xiàn)程要修改UI組件的時(shí)候,就需要借助Handler消息機制了。
Handle發(fā)送和處理消息的幾個(gè)方法:
1. void handleMessage(Message msg):處理消息的方法,該方法通常被重寫(xiě)。
2.final boolean hasMessage(int what):檢查消息隊列中是否包含有what屬性為指定值的消息
3.final boolean hasMessage(int what ,Object object) :檢查消息隊列中是否包含有what好object屬性指定值的消息
4.sendEmptyMessage(int what):發(fā)送空消息
5.final Boolean send EmptyMessageDelayed(int what ,long delayMillis):指定多少毫秒發(fā)送空消息
6.final boolean sendMessage(Message msg):立即發(fā)送消息
7.final boolean sendMessageDelayed(Message msg,long delayMillis):多少秒之后發(fā)送消息
與Handle工作的幾個(gè)組件Looper、MessageQueue各自的作用:
1.Handler:它把消息發(fā)送給Looper管理的MessageQueue,并負責處理Looper分給它的消息
2.MessageQueue:采用先進(jìn)的方式來(lái)管理Message
3.Looper:每個(gè)線(xiàn)程只有一個(gè)Looper,比如UI線(xiàn)程中,系統會(huì )默認的初始化一個(gè)Looper對象,它負責管理MessageQueue,不斷的從MessageQueue中取消息,并將
相對應的消息分給Handler處理
在線(xiàn)程中使用Handler的步驟:
1.調用Looper的prepare()方法為當前線(xiàn)程創(chuàng )建Looper對象,創(chuàng )建Looper對象時(shí),它的構造器會(huì )自動(dòng)的創(chuàng )建相對應的MessageQueue
2.創(chuàng )建Handler子類(lèi)的實(shí)例,重寫(xiě)HandleMessage()方法,該方法處理除UI線(xiàn)程以外線(xiàn)程的消息
3.調用Looper的loop()方法來(lái)啟動(dòng)Looper
實(shí)例
xmlns:tools=http://schemas.android.com/tools
android:layout_width=match_parent
android:layout_height=match_parent
android:paddingBottom=@dimen/activity_vertical_margin
android:paddingLeft=@dimen/activity_horizontal_margin
android:paddingRight=@dimen/activity_horizontal_margin
android:paddingTop=@dimen/activity_vertical_margin
tools:context=.MainActivity >
android:id=@+id/ed1
android:layout_width=match_parent
android:layout_height=wrap_content
android:inputType=number />
android:id=@+id/Ok
android:layout_width=match_parent
android:layout_height=wrap_content
android:layout_below=@id/ed1
android:text=@string/Ok />
android:id=@+id/next
android:layout_width=match_parent
android:layout_height=wrap_content
android:layout_below=@id/Ok
android:text=下一張 />
android:id=@+id/image1
android:layout_width=match_parent
android:layout_height=match_parent
android:layout_below=@id/next
android:src=@drawable/a3 />
評論