In-depth analysis of message loops in Android Handler

Source: Internet
Author: User

Handler is a class used to operate message queues within a thread. This is a bit difficult. Let's talk about it slowly. As mentioned in the previous article, logoff is used to create a message queue for a thread. That is to say, logoff can make MessageQueue affiliated to the thread and loop the message queue, receives and processes messages. However, we do not directly operate message queues, but use Handler to operate message queues, send messages to message queues, and retrieve and process messages from message queues. This is Handler's responsibility.
Handler, logoff, and MessageQueue belong to the internal data of a thread, but they provide interfaces for external threads to access. Handler is the interface that exposes data to external threads and communicates with threads. In other words, these three things are used for Communication between threads (ITC -- Inter Thread Communication) and intercommunication (IPC -- Inter Process Communication) the core idea of Message Queue msgque is consistent. MessageQueue is relatively low-level and rarely used directly. logoff and Handler are specifically used to operate the underlying MessageQueue.
Another important data structure is the basic element of communication, namely, the Message object (Message), which is never used independently and is used by Handler. For details, refer to the document. However, you must note that the same message object cannot be sent twice. Otherwise, AndroidRuntimeException: {what = 1000 when =-15 ms obj =...} may occur ..} this message is already in use. ". Before sending a Message, you must use Message. obtain () to obtain a new object. Alternatively, Handler. sendEmptyMessage (int) can be used to directly send an empty Message without sending additional data ). In addition, you must note that the Message object cannot be recycled manually, that is, you cannot call the Message. recycle () to release a message object, because after the object is removed from the queue for processing, MessageQueue automatically performs recycle (). This is easy to understand, because after a message is sent to the message queue, the message will be processed when it is unknown to the application. Only MessageQueue will know, therefore, MessageQueue can only be used for release recovery.
Because Handler is used to operate the Message Queue inside a thread, Handler must be attached to one thread and can only be one thread. In other words, you must create a Handler in a thread and specify the callback handlerMessage (Message msg) of the Handler ).
Handler has two main purposes: one is used for the internal message loop of the thread; the other is used for inter-thread communication.
For the basic usage of Handler, refer to the document.
Used for message loop within a thread
It is mainly used to perform an action at a scheduled time in the future, or cyclically and cyclically. The main interface is
Handler. sendEmptyMessageDelayed (int msgid, long after );
Handler. sendMessageDelayed (Message msg, long after );
Handler. postDelayed (Runnable task, long after );
Handler. sendMessageAtTime (Message msg, long timeMillis );
Handler. sendEmptyMessageAtTime (int id, long timeMiilis );
Handler. postAtTime (Runnable task, long timeMillis );
The purpose of these methods is to set a timer to send messages to the MessageQueue of the Handler after the specified time or at the specified time. In this way, it is very convenient for the application to implement scheduled operations or cyclic timing operations (messages are sent in a delayed manner when messages are processed to achieve cyclic timing ).

This is not difficult to use, but it should be noted that the message loop in the thread is not processed concurrently, that is, all messages are processed in the thread to which the Handler belongs, therefore, although you use post (Runnable r) to send MessageQueue a Runnable, this does not create a new thread for execution. When processing this message, only r is called. run (). (To execute another Thread, you must put Runnable in a Thread ).
Instance
Here, an instance is used to show that the main thread communicates with the background thread through Handler, and the main thread uses Handler to implement the loop sequence.

Play a video. The thread is used to create and initialize the MediaPlayer. After initialization, the main thread is notified through the Handler of the main thread. Then, the main thread can play the video and use sendMessageDelayed () during playback () to continuously update the playback progress:Copy codeThe Code is 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 (Message 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 is 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.