天天看點

Android Handler機制(不含源碼解析,适合新手了解)一、官方解釋二、個人了解(簡書Handler作用與機制)

一、官方解釋

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);
            }
        });
    }
}
           

下面是點選的效果圖

點選前

Android Handler機制(不含源碼解析,适合新手了解)一、官方解釋二、個人了解(簡書Handler作用與機制)

點選前.png

點選之後

Android Handler機制(不含源碼解析,适合新手了解)一、官方解釋二、個人了解(簡書Handler作用與機制)

點選後.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);
            }
        });
    }
}
           

下面是效果圖:

點選前就不貼了,直接上點選後的吧。

Android Handler機制(不含源碼解析,适合新手了解)一、官方解釋二、個人了解(簡書Handler作用與機制)

image.png

Handler中有很多消息,可以發送空消息,實體消息,還有延遲發送。

具體的使用可以去官方文檔上看,或者百度,我這裡僅僅貼出基本使用,和經常使用。

如果不足和建議,歡迎提出。

我的部落格即将入駐“雲栖社群”,誠邀技術同仁一同入駐。

繼續閱讀