Android:Handler 概念理解与运用

本文详细介绍了Android中Handler类的功能和使用方法,包括如何利用Handler进行异步操作、发送消息和Runnable对象,以及如何处理这些任务。同时,还提供了Handler类中关键方法的解释。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

       android.od.Handler是android SDK 处理定时操作的核心类。能够完成异步操作。

通过Handler类,可以提交和处理一个Runnable对象。

这个对象的run方法可以立即执行,也可以在指定的时间执行。

handler类允许你发送消息和处理线程队列中的消息及Runnable对象。

handler实例都是与一个线程和该线程的消息队列一起使用的。一旦创建一个新的handler的实例,系统就会把该实例与一个线程和该线程的消息队列捆绑起来,才可以发送消息和Runnable对象给消息队列,并在消息队列的出口处 处理它们;

         handler在把runnable对象放到队列中之后运行的时候,他不是生成另外一个线程来运行的;

下面是几个常用的方法:

post

public final boolean post(Runnable r)
Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.
将一个Runnable对象r,放到消息队列中去。当handler逮到它的时候,将会在线程里面运行。

 

postDelayed

public final boolean postDelayed(Runnable r,
                                 long delayMillis)
Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. The runnable will be run on the thread to which this handler is attached.
把一个Runable的对象放到消息队列中,并且在时间delayMillis之后,运行。
 

sendMessage

public final boolean sendMessage(Message msg)
Pushes a message onto the end of the message queue after all pending messages before the current time. It will be received in handleMessage(android.os.Message), in the thread attached to this handler.
将一个消息,放到队列的尾端。将会被handleMessage(msg)方法取得

 

handleMessage

public void handleMessage(Message msg)
Subclasses must implement this to receive messages.
在子类中,这个方法必须被实现,才能用于接收消息
 

removeCallbacks

public final void removeCallbacks(Runnable r)
Remove any pending posts of Runnable r that are in the message queue.
把队列里面的Runnable对象移除。清空

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值