An in-depth analysis of the message cycle of Android handler _android

Source: Internet
Author: User
Tags message queue
Handler is a class that is used to manipulate message queues within a thread. It's a bit round, it's okay, let's take it slow. The previous looper mentioned that Looper is used to create message queues for threads, that is, looper can allow Message Queuing (MessageQueue) to be attached to a thread, and let message queues loop to receive and process messages. But instead of manipulating Message Queuing directly, we use handler to manipulate message queues, send messages to message queues, and take messages out of message queues and process them. This is the duty of handler.
Handler,looper and MessageQueue are data that belong within a thread, but it provides an interface that is accessible to external threads, and handler is the interface that is exposed to external threads and communicates with threads. In other words, these three things are used to communicate between threads (Itc--inter thread communication), and to communicate (Ipc--inter Process communication) The core idea of the message queue Msgque is consistent. MessageQueue is relatively lower level, less direct use, Looper and handler are specifically used to operate the bottom MessageQueue.
Another important data structure is the basic element of communication, the message object, which is never used alone, and is used by handler. The specific method can refer to the document, but note that the same message object can not be sent two times, otherwise there will be androidruntimeexception: {what=1000 when=-15ms obj= ...} This am already in use. ". Each time you send a message, you get a new object by Message.obtain (), or you can send a null message directly without sending additional data handler.sendemptymessage (int). Also note that message objects cannot be recycled manually, meaning that you cannot invoke Message.recycle () to release a Message object, because when the object is removed from the queue, the MessageQueue automatically does the recycle (). This is also easy to understand, because when sending a message to a message queue, when the message will be processed, for the application is not aware of, only MessageQueue will know, so only by MessageQueue to do the act of recycling.
Because handler is used to manipulate message queues within a thread, handler must be attached to one thread and only one thread. In other words, you must create a handler in a line agenda and specify handler callback Handlermessage (Message msg).
Handler has two main uses, one for thread internal message loops, and one for thread communication.
The basic usage of handler can refer to the document, it is quite clear.
for thread internal message loops
It is mainly used to do some action in the future, or to cycle, periodically to do some action. The main interface is
handler.sendemptymessagedelayed (int msgid, long after);
Handler.sendmessagedelayed (msg, long after);
Handler.postdelayed (Runnable task, long after);
Handler.sendmessageattime (msg, long Timemillis);
Handler.sendemptymessageattime (int id, long timemiilis);
Handler.postattime (Runnable task, long Timemillis);
The purpose of these methods is to set up a timer to send a message to the MessageQueue where the handler is located after a specified time, or at a specified time. This makes it very convenient for the application to implement timed operations, or to cycle the time sequence (when processing the message to delay sending messages to achieve the cyclic timing).

This is not difficult to use, but it should be noted that the thread internal message loop is not concurrent processing, that is, all messages are handled within the thread that handler belongs to, so although you use post (Runnable R), send MessageQueue a Runnable , but this does not create a new thread to execute, when this message is processed only by invoking R.run (). (You must put the runnable in a thread if you want to execute it on another.)
Instance
Here we use an example to show that the main thread communicates with the background thread through handler, and the main thread uses handler to implement the cyclic timing.

Play a video, the thread used to create and initialize the MediaPlayer, the initialization will be through the main thread of the handler told the main thread, and then the main thread can play the video, in the playback process through the sendmessagedelayed () to achieve the continuous update of playback progress:
Copy Code code as follows:

public class Handlersimpledemo extends activity {
Protected static final String TAG = "Handlersimpledemo";
private static final int media_player_ready = 0;
private static final int refresh_progress = 1;

Private Button Mstart;
Private Button mstop;
Private Surfaceholder Msurfaceholder;
Private ProgressBar Mprogressbar;
Private Surfaceview Mdisplay;
Private MediaPlayer Mmediaplayer;

Private Handler Mmainhandler = new Handler () {
@Override
public void Handlemessage (msg) {
Switch (msg.what) {
Case Media_player_ready:
Mprogressbar.setmax (Mmediaplayer.getduration ());
Mmediaplayer.setoncompletionlistener (New Mediaplayer.oncompletionlistener () {
public void Oncompletion (MediaPlayer MP) {
Mprogressbar.setprogress (Mmediaplayer.getduration ());
Mmainhandler.removemessages (refresh_progress);
}
});
Mstart.setenabled (TRUE);
Mstop.setenabled (TRUE);
Break
Case Refresh_progress:
int cp = Mmediaplayer.getcurrentposition ();
Mprogressbar.setprogress (CP);
int delay = 1000-(cp% 1000);
Mmainhandler.sendemptymessagedelayed (refresh_progress, delay);
Break
Default
Break
}
}
};

@SuppressWarnings ("deprecation")
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.handler_simple_demo);
Mstart = (Button) Findviewbyid (R.id.handler_simple_start);
Mstart.setonclicklistener (New View.onclicklistener () {
public void OnClick (View v) {
Mmediaplayer.start ();
Mmainhandler.sendemptymessage (refresh_progress);
}
});
Mstart.setenabled (FALSE);
Mstop = (Button) Findviewbyid (r.id.handler_simple_stop);
Mstop.setonclicklistener (New View.onclicklistener () {
public void OnClick (View v) {
Mmainhandler.removemessages (refresh_progress);
Mmediaplayer.pause ();
}
});
Mstop.setenabled (FALSE);
Mprogressbar = (ProgressBar) Findviewbyid (r.id.handler_simple_progress);
Mdisplay = (Surfaceview) Findviewbyid (R.id.handler_simple_display);
Msurfaceholder = Mdisplay.getholder ();
Msurfaceholder.setfixedsize (Mdisplay.getwidth (), Mdisplay.getheight ());
Do not believe the document, SetType are necessary, otherwise, video won ' t play correctly
Msurfaceholder.settype (surfaceholder.surface_type_push_buffers);

New Thread (New Runnable () {
public void Run () {
try {
Mmediaplayer = Mediaplayer.create (Getapplication (), r.raw.flug);
Mmediaplayer.setdisplay (Msurfaceholder);
Mmainhandler.sendemptymessage (Media_player_ready);
catch (IllegalArgumentException e) {
LOG.E (TAG, "Caught Exception e", E);
catch (SecurityException e) {
LOG.E (TAG, "Caught Exception e", E);
catch (IllegalStateException e) {
LOG.E (TAG, "Caught Exception e", E);
}
}
). Start ();
}
@Override
protected void OnDestroy () {
Super.ondestroy ();
Mmainhandler.removemessages (refresh_progress);
if (Mmediaplayer!= null) {
Mmediaplayer.release ();
}
}
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.