Android Handler机制(不含源码解析,适合新手理解)

简介: 一、官方解释A Handler allows you to send and process [Message](https://developer.

一、官方解释

A Handler allows you to send and process [Message](https://developer.android.com/reference/android/os/Message.html) and Runnable objects associated with a thread's [MessageQueue](https://developer.android.com/reference/android/os/MessageQueue.html). Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
There are two main uses for a Handler: (1) to schedule messages and runnables to be executed at some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.
Scheduling messages is accomplished with the [post(Runnable)](https://developer.android.com/reference/android/os/Handler.html#post(java.lang.Runnable)), [postAtTime(Runnable, long)](https://developer.android.com/reference/android/os/Handler.html#postAtTime(java.lang.Runnable,%20long)),[postDelayed(Runnable, Object, long)](https://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable,%20java.lang.Object,%20long)), [sendEmptyMessage(int)](https://developer.android.com/reference/android/os/Handler.html#sendEmptyMessage(int)), [sendMessage(Message)](https://developer.android.com/reference/android/os/Handler.html#sendMessage(android.os.Message)), [sendMessageAtTime(Message, long)](https://developer.android.com/reference/android/os/Handler.html#sendMessageAtTime(android.os.Message,%20long)), and [sendMessageDelayed(Message, long)](https://developer.android.com/reference/android/os/Handler.html#sendMessageDelayed(android.os.Message,%20long)) methods. The post versions allow you to enqueue Runnable objects to be called by the message queue when they are received; the sendMessageversions allow you to enqueue a [Message](https://developer.android.com/reference/android/os/Message.html) object containing a bundle of data that will be processed by the Handler's [handleMessage(Message)](https://developer.android.com/reference/android/os/Handler.html#handleMessage(android.os.Message)) method (requiring that you implement a subclass of Handler).
When posting or sending to a Handler, you can either allow the item to be processed as soon as the message queue is ready to do so, or specify a delay before it gets processed or absolute time for it to be processed. The latter two allow you to implement timeouts, ticks, and other timing-based behavior.
When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, broadcast receivers, etc) and any windows they create. You can create your own threads, and communicate back with the main application thread through a Handler. This is done by calling the same post or sendMessage methods as before, but from your new thread. The given Runnable or Message will then be scheduled in the Handler's message queue and processed when appropriate.


翻译:

处理程序允许您发送和处理与线程的MessageQueue相关联的消息和可运行对象。每个处理程序实例都与单个线程和线程的消息队列相关联。当您创建一个新的Handler时,它将绑定到正在创建它的线程的线程/消息队列——从那时起,它将向该消息队列传递消息和可运行文件,并在它们从消息队列中出来时执行它们。

处理程序有两种主要用途:(1)调度消息和将来某个时间点要执行的可运行文件;(2)为要在不同线程上执行的操作排队。

调度消息是通过post(Runnable)、postAtTime(Runnable,long)、postDelayed(Runnable,Object,long)、sendEmptyMessage(int)、sendMessage(Message)、sendMessageAtTime(Message,long)和sendMessageDelayed(Message,long)方法完成的。post版本允许您在收到消息队列时对要由消息队列调用的Runable对象进行排队;sendMessage版本允许您对消息对象进行排队,该消息对象包含将由Handler的handleMessage(Message)方法处理的数据束(需要实现汉德勒的一个亚类。
当发布或发送给处理程序时,您可以允许在消息队列准备就绪时立即处理项,或者指定在处理项之前的延迟或处理项的绝对时间。后两者允许您实现超时、滴答和其他基于时间的行为。
在为应用程序创建进程时,其主线程专用于运行消息队列,该队列负责管理顶级应用程序对象(活动、广播接收器等)及其创建的任何窗口。您可以创建自己的线程,并通过处理程序与主应用程序线程通信。这是通过调用相同的POST或SeNeMeST方法与以前一样,但是从新线程中调用。然后,给定的可运行或消息将被安排在处理程序的消息队列中,并在适当的时候进行处理。


装逼结束

二、个人理解(简书Handler作用与机制)

Handler,用于发送消息和处理消息。我们在开发中使用Handler一般用于更新UI,或者延时处理事件。 包括但不限于。

Handler机制,其工作核心主要包括四大部分:

Message、MessageQueue、Looper、Handler。这四大部分

其工作流程大致如下:

创建 消息(Massage ),
将消息存到消息队列(MessageQueue)当中,
由消息泵(Looper)将消息从消息队列中抽取出来,
并且交给Handler处理。


来个实践Demo感受一下吧。
代码如下:
注:xml代码我就不贴了,就是一个Button一个TextView。

public class MainActivity extends AppCompatActivity {
    Button button;
    TextView textView;
    private final int HANDLER_FLAG = 1;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HANDLER_FLAG:
                    textView.setText("我的点击后的值");
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = findViewById(R.id.main_btn);
        textView = findViewById(R.id.main_tv);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.sendEmptyMessage(HANDLER_FLAG);
            }
        });
    }
}

下面是点击的效果图

点击前


img_67418cbc4cc40e4504fbacfd9931be9c.png
点击前.png

点击之后


img_721d690a366e574a0120e4e5f4b13fd8.png
点击后.png

不仅仅可以用死值,当然也可以传值:

public class MainActivity extends AppCompatActivity {

    Button button;
    TextView textView;
    private final int HANDLER_FLAG = 1;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HANDLER_FLAG:
                    textView.setText(msg.obj.toString() + "");
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = findViewById(R.id.main_btn);
        textView = findViewById(R.id.main_tv);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Message message = new Message();
                message.obj = "这是点击后的值11111";
                message.what = HANDLER_FLAG;
                handler.sendMessage(message);
            }
        });
    }
}

下面是效果图:
点击前就不贴了,直接上点击后的吧。


img_a2ee8058beaad76470bca501975425a3.png
image.png

Handler中有很多消息,可以发送空消息,实体消息,还有延迟发送。
具体的使用可以去官方文档上看,或者百度,我这里仅仅贴出基本使用,和经常使用。

如果不足和建议,欢迎提出。


我的博客即将入驻“云栖社区”,诚邀技术同仁一同入驻。

相关文章
|
20天前
|
PHP 项目管理 开发者
深入解析PHP的命名空间和自动加载机制
【4月更文挑战第4天】 在PHP的编程世界中,命名空间和自动加载机制是构建大型应用程序时不可或缺的工具。本文将深入探讨这两个概念,揭示它们如何简化代码结构、避免类名冲突以及提高代码维护性。通过对PHP命名空间的由来、作用域和使用方法的细致剖析,以及对自动加载机制工作原理和应用实践的全面讲解,读者将获得有效管理复杂项目中依赖关系的能力。
|
22天前
|
XML Java Android开发
Android实现自定义进度条(源码+解析)
Android实现自定义进度条(源码+解析)
51 1
|
22天前
|
Java Android开发
Android反编译查看源码
Android反编译查看源码
23 0
|
1天前
|
Linux 开发工具 Android开发
Docker系列(1)安装Linux系统编译Android源码
Docker系列(1)安装Linux系统编译Android源码
3 0
|
2天前
|
JSON 编译器 开发工具
VS Code阅读Android源码
VS Code阅读Android源码
9 1
|
12天前
|
算法 Linux 调度
深度解析:Linux内核的进程调度机制
【4月更文挑战第12天】 在多任务操作系统如Linux中,进程调度机制是系统的核心组成部分之一,它决定了处理器资源如何分配给多个竞争的进程。本文深入探讨了Linux内核中的进程调度策略和相关算法,包括其设计哲学、实现原理及对系统性能的影响。通过分析进程调度器的工作原理,我们能够理解操作系统如何平衡效率、公平性和响应性,进而优化系统表现和用户体验。
20 3
|
29天前
|
监控 算法 Unix
【Linux 异步操作】深入理解 Linux 异步通知机制:原理、应用与实例解析
【Linux 异步操作】深入理解 Linux 异步通知机制:原理、应用与实例解析
60 0
|
7天前
yolo-world 源码解析(六)(2)
yolo-world 源码解析(六)
18 0
|
7天前
yolo-world 源码解析(六)(1)
yolo-world 源码解析(六)
12 0
|
8天前
yolo-world 源码解析(五)(4)
yolo-world 源码解析(五)
19 0

推荐镜像

更多