新闻中心

EEPW首页 > 嵌入式系统 > 设计应用 > Android之Handler消息机制

Android之Handler消息机制

作者:时间:2016-10-10来源:网络收藏

Android中Handle类的主要作用:

本文引用地址:http://www.eepw.com.cn/article/201610/306009.htm

1.在新启动的线程中发送给消息

2.在主线程获取、处理消息

为什么要用Handle这样的一个机制:

因为在Android系统中UI操作并不是线程安全的,如果多个线程并发的去操作同一个组件,可能导致线程安全问题。为了解决这一个问题,制定了一条规则:只允许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

实例

xmlns:tools=http://schemas..com/tools

: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 />



关键词: android handler

评论


相关推荐

技术专区

关闭