歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android之Handler消息機制

Android之Handler消息機制

日期:2017/3/1 9:51:45   编辑:Linux編程

Android中Handle類的主要作用:

1.在新啟動的線程中發送給消息

2.在主線程獲取、處理消息

為什麼要用Handle這樣的一個機制:

因為在Android系統中UI操作並不是線程安全的,如果多個線程並發的去操作同一個組件,可能導致線程安全問題。為了解決這一個問題,android制定了一條規則:只允許UI線程來修改UI組件的屬性等,也就是說必須單線程模型,這樣導致如果在UI界面進行一個耗時叫長的數據更新等就會形成程序假死現象 也就是ANR異常,如果20秒中沒有完成程序就會強制關閉。所以比如另一個線程要修改UI組件的時候,就需要借助Handler消息機制了。

Handle發送和處理消息的幾個方法:

1. void handleMessage(Message msg):處理消息的方法,該方法通常被重寫。

2.final boolean hasMessage(int what):檢查消息隊列中是否包含有what屬性為指定值的消息

3.final boolean hasMessage(int what ,Object object) :檢查消息隊列中是否包含有what好object屬性指定值的消息

4.sendEmptyMessage(int what):發送空消息

5.final Boolean send EmptyMessageDelayed(int what ,long delayMillis):指定多少毫秒發送空消息

6.final boolean sendMessage(Message msg):立即發送消息

7.final boolean sendMessageDelayed(Message msg,long delayMillis):多少秒之後發送消息

與Handle工作的幾個組件Looper、MessageQueue各自的作用:

1.Handler:它把消息發送給Looper管理的MessageQueue,並負責處理Looper分給它的消息

2.MessageQueue:采用先進的方式來管理Message

3.Looper:每個線程只有一個Looper,比如UI線程中,系統會默認的初始化一個Looper對象,它負責管理MessageQueue,不斷的從MessageQueue中取消息,並將

相對應的消息分給Handler處理

在線程中使用Handler的步驟:

1.調用Looper的prepare()方法為當前線程創建Looper對象,創建Looper對象時,它的構造器會自動的創建相對應的MessageQueue

2.創建Handler子類的實例,重寫HandleMessage()方法,該方法處理除UI線程以外線程的消息

3.調用Looper的loop()方法來啟動Looper

實例

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
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" > <EditText
android:id="@+id/ed1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number" /> <Button
android:id="@+id/Ok"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/ed1"
android:text="@string/Ok" />
<Button
android:id="@+id/next"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/Ok"
android:text="下一張" /> <ImageView
android:id="@+id/image1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/next"
android:src="@drawable/a3" /> </RelativeLayout>

更多詳情見請繼續閱讀下一頁的精彩內容: http://www.linuxidc.com/Linux/2013-10/92027p2.htm

Copyright © Linux教程網 All Rights Reserved