Reprinted from: https://www.10qianwan.com/articledetail/809922.html
Detailed explanation of Android Handler use case
What is a handler? Handler can send and process message objects or runnable objects, which are associated with a thread. Each instance of handler is associated with a thread and a thread's message queue. When created
(adsbygoogle = window.adsbygoogle || []).push({});
What is a handler?
Handler can send and process message objects or runnable objects, which are associated with a thread. Each instance of handler is associated with a thread and a thread's message queue. When a handler object is created, a thread or message queue is also created. The handler object will send and process these messages or runnable objects.
The handler class has two main purposes:
- To execute the runnable object, you can also set the delay.
- Sending messages between two threads is mainly used to send messages to the main thread to update the ui.
Why use handler
To solve the problem of multithreading concurrency, suppose that in an activity, there are multiple threads to update the ui, and there is no locking mechanism, the interface display will certainly be abnormal. Therefore, andoird officially encapsulates a set of ui update mechanism, and can also use handler to send messages between multiple threads.
How to use handler
The following methods are commonly used by handler:
post(runnable) postattime(runnable,long) postdelayed(runnable,long) sendemptymessage(int) sendmessage(message) sendmessageattime(message,long) sendmessagedelayed(message,long)
We can see that these methods are mainly divided into two categories: one is to pass in a runnable object, and the other is to pass in a message object.
Use code to learn post a runnable object
First create a handler object and directly create a new one
private handler handler=new handler();
Implement the runnable interface, use anonymous implementation, rewrite the run method, and print a string.
private runnable runnable=new runnable() { @override public void run() { log.i("mainactivity","handler runnable"); } };
Then we call the handler's post method. Note that post is a runnable object. The bottom layer uses a callback and will not start a new thread. All runnable run methods are still in the main thread. You can update the ui.
handler.post(runnable);//implement handler.postdelayed(runnable,2000);//Execute after 2 seconds delay
Run the program, and the log printed on the console is as follows:
05-18 19:17:14.901 17750-17750/com.ansen.handler i/mainactivity: handler runnable 05-18 19:17:16.901 17750-17750/com.ansen.handler i/mainactivity: handler runnable
From the above log, we can see that the time difference between the two logs is two seconds. This is because when we use the postdelayed method, the second parameter sets a two second delay.
Use the sendmessage method to deliver messages
From the name of the method, we can understand that it is used to send messages. This method is frequently used in android, because the ui cannot be updated in multiple threads in android. You must pass the message to the ui thread through the handler to update the ui. Of course, you can also use handler to send messages to two sub threads.
We give activity_ Set an id for the textview control in the main file, then find the control in the mainactivity, and assign a value to the textview in the multithreaded for loop. The added code is as follows:
textview= (textview) findviewbyid(r.id.textview); new thread(new runnable(){ @override public void run(){ for(int i=1;i<=100;i++){ log.i("mainactivity","The current value is:"+i); textview.settext("The current value is:"+i); try { thread.sleep(200); } catch (interruptedexception e) { e.printstacktrace(); } } } }).start();
Rerun the code and the program crashes. The console prints the following log:
android.view.viewrootimpl$calledfromwrongthreadexception: only the original thread that created a view hierarchy can touch its views. at android.view.viewrootimpl.checkthread(viewrootimpl.java:6024) at android.view.viewrootimpl.requestlayout(viewrootimpl.java:820)
This is because the ui cannot be updated in multiple threads in android.
When each application starts, android will start a corresponding main thread to handle ui related events, such as user key events, user touch screen events and screen drawing events, and distribute relevant events to corresponding components for processing. Therefore, the main thread is usually called ui thread.
At this time, we will use android's handle class. Handle can help us solve the problem that multithreading cannot update ui. Here, we just need to know how to use this class. We will introduce its principle in detail later.
Next, let's look at how to use the handler to accept messages from child threads in the main thread and update the ui. First, when creating a new handler, implement its handlemessage method. The modified code is as follows:
private handler handler=new handler(){ @override public void handlemessage(message msg) { if(msg.what==update_ui){ textview.settext("The current value is:"+msg.obj); } } };
We can see that the code for updating textview is put here, and the msg parameter of handlemessage is used. This object usually has two properties. what is an indicator. When we send a message, we must specify a value. obj: parameter for sending message.
Let's see what changes have been made to the multi-threaded run method. First, call the obtainmessage method. This method returns a message object from the message pool. If the message pool does not have an object, it will create an object, so as to avoid going to the new message object all the time. The message object has a what attribute, which must be assigned. It is an int type. As we mentioned earlier, it is a sign. obj is used to send messages to pass parameters. Here we pass in the value of i. Finally, call handler.. SendMessage (message) method. Then our handler's handlemessage method will call back.
new thread(new runnable(){ @override public void run(){ for(int i=1;i<=100;i++){ log.i("mainactivity","The current value is:"+i); message message=handler.obtainmessage(); message.what=update_ui; message.obj=i; handler.sendmessage(message); try { thread.sleep(200); } catch (interruptedexception e) { e.printstacktrace(); } } } }).start();
There are also sendemptymessage and sendmessagedelayed methods. I won't explain them to you one by one. If you are interested, please implement them yourself.